diff --git a/dist/xeokit-sdk.cjs.js b/dist/xeokit-sdk.cjs.js index 887eee681..a83e34b4e 100644 --- a/dist/xeokit-sdk.cjs.js +++ b/dist/xeokit-sdk.cjs.js @@ -12170,6 +12170,10 @@ class AngleMeasurementsMouseControl extends AngleMeasurementsControl { const mouseWorldPos = math.vec3(); const mouseHoverCanvasPos = math.vec2(); this._currentAngleMeasurement = null; + + const getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent)); + const getLeft = el => el.offsetLeft + (el.offsetParent && getLeft(el.offsetParent)); + this._onMouseHoverSurface = cameraControl.on( this._snapping ? "hoverSnapOrSurface" @@ -12201,13 +12205,9 @@ class AngleMeasurementsMouseControl extends AngleMeasurementsControl { mouseHoverCanvasPos.set(canvasPos); switch (this._mouseState) { case MOUSE_FINDING_ORIGIN: - const canvasBoundRect = canvas.getBoundingClientRect(); - const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; - const scrollTop = window.pageYOffset || document.documentElement.scrollTop; - const canvasLeftEdge = canvasBoundRect.left + scrollLeft; - const canvasTopEdge = canvasBoundRect.top + scrollTop; - this.markerDiv.style.left = `${canvasLeftEdge + canvasPos[0] - 5}px`; - this.markerDiv.style.top = `${canvasTopEdge + canvasPos[1] - 5}px`; + this.markerDiv.style.left = `${getLeft(canvas) + canvasPos[0] - 5}px`; + this.markerDiv.style.top = `${getTop(canvas) + canvasPos[1] - 5}px`; + break; case MOUSE_FINDING_CORNER: if (this._currentAngleMeasurement) { @@ -85987,6 +85987,9 @@ class DistanceMeasurementsMouseControl extends DistanceMeasurementsControl { this._mouseState = MOUSE_FIRST_CLICK_EXPECTED; + const getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent)); + const getLeft = el => el.offsetLeft + (el.offsetParent && getLeft(el.offsetParent)); + this._onCameraControlHoverSnapOrSurface = cameraControl.on( this._snapping ? "hoverSnapOrSurface" @@ -85997,16 +86000,8 @@ class DistanceMeasurementsMouseControl extends DistanceMeasurementsControl { pointerCanvasPos.set(event.canvasPos); if (this._mouseState === MOUSE_FIRST_CLICK_EXPECTED) { - // const canvasBoundary = getCanvasBoundary(); - - const canvasBoundRect = canvas.getBoundingClientRect(); - const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; - const scrollTop = window.pageYOffset || document.documentElement.scrollTop; - const canvasLeftEdge = canvasBoundRect.left + scrollLeft; - const canvasTopEdge = canvasBoundRect.top + scrollTop; - - this._markerDiv.style.left = `${canvasLeftEdge + canvasPos[0] - 5}px`; - this._markerDiv.style.top = `${canvasTopEdge + canvasPos[1] - 5}px`; + this._markerDiv.style.left = `${getLeft(canvas) + canvasPos[0] - 5}px`; + this._markerDiv.style.top = `${getTop(canvas) + canvasPos[1] - 5}px`; this._markerDiv.style.background = "pink"; if (event.snappedToVertex || event.snappedToEdge) { diff --git a/dist/xeokit-sdk.es.js b/dist/xeokit-sdk.es.js index 171213c8b..03e06cf72 100644 --- a/dist/xeokit-sdk.es.js +++ b/dist/xeokit-sdk.es.js @@ -12166,6 +12166,10 @@ class AngleMeasurementsMouseControl extends AngleMeasurementsControl { const mouseWorldPos = math.vec3(); const mouseHoverCanvasPos = math.vec2(); this._currentAngleMeasurement = null; + + const getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent)); + const getLeft = el => el.offsetLeft + (el.offsetParent && getLeft(el.offsetParent)); + this._onMouseHoverSurface = cameraControl.on( this._snapping ? "hoverSnapOrSurface" @@ -12197,13 +12201,9 @@ class AngleMeasurementsMouseControl extends AngleMeasurementsControl { mouseHoverCanvasPos.set(canvasPos); switch (this._mouseState) { case MOUSE_FINDING_ORIGIN: - const canvasBoundRect = canvas.getBoundingClientRect(); - const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; - const scrollTop = window.pageYOffset || document.documentElement.scrollTop; - const canvasLeftEdge = canvasBoundRect.left + scrollLeft; - const canvasTopEdge = canvasBoundRect.top + scrollTop; - this.markerDiv.style.left = `${canvasLeftEdge + canvasPos[0] - 5}px`; - this.markerDiv.style.top = `${canvasTopEdge + canvasPos[1] - 5}px`; + this.markerDiv.style.left = `${getLeft(canvas) + canvasPos[0] - 5}px`; + this.markerDiv.style.top = `${getTop(canvas) + canvasPos[1] - 5}px`; + break; case MOUSE_FINDING_CORNER: if (this._currentAngleMeasurement) { @@ -85983,6 +85983,9 @@ class DistanceMeasurementsMouseControl extends DistanceMeasurementsControl { this._mouseState = MOUSE_FIRST_CLICK_EXPECTED; + const getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent)); + const getLeft = el => el.offsetLeft + (el.offsetParent && getLeft(el.offsetParent)); + this._onCameraControlHoverSnapOrSurface = cameraControl.on( this._snapping ? "hoverSnapOrSurface" @@ -85993,16 +85996,8 @@ class DistanceMeasurementsMouseControl extends DistanceMeasurementsControl { pointerCanvasPos.set(event.canvasPos); if (this._mouseState === MOUSE_FIRST_CLICK_EXPECTED) { - // const canvasBoundary = getCanvasBoundary(); - - const canvasBoundRect = canvas.getBoundingClientRect(); - const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; - const scrollTop = window.pageYOffset || document.documentElement.scrollTop; - const canvasLeftEdge = canvasBoundRect.left + scrollLeft; - const canvasTopEdge = canvasBoundRect.top + scrollTop; - - this._markerDiv.style.left = `${canvasLeftEdge + canvasPos[0] - 5}px`; - this._markerDiv.style.top = `${canvasTopEdge + canvasPos[1] - 5}px`; + this._markerDiv.style.left = `${getLeft(canvas) + canvasPos[0] - 5}px`; + this._markerDiv.style.top = `${getTop(canvas) + canvasPos[1] - 5}px`; this._markerDiv.style.background = "pink"; if (event.snappedToVertex || event.snappedToEdge) { diff --git a/dist/xeokit-sdk.es5.js b/dist/xeokit-sdk.es5.js index 76fd2036b..bfef91380 100644 --- a/dist/xeokit-sdk.es5.js +++ b/dist/xeokit-sdk.es5.js @@ -2988,7 +2988,7 @@ _this18._initMarkerDiv();_this18._onMouseHoverSurface=null;_this18._onHoverNothi */function get(){return this._snapping;}/** * Activates this AngleMeasurementsMouseControl, ready to respond to input. */,set:function set(snapping){if(snapping!==this._snapping){this._snapping=snapping;this.deactivate();this.activate();}else{this._snapping=snapping;}}},{key:"activate",value:function activate(){var _this19=this;if(this._active){return;}if(!this.markerDiv){this._initMarkerDiv();// if the marker is destroyed after deactivation, we recreate it -}this.angleMeasurementsPlugin;var scene=this.scene;scene.input;var canvas=scene.canvas.canvas;var clickTolerance=20;var cameraControl=this.angleMeasurementsPlugin.viewer.cameraControl;var pointerLens=this.pointerLens;var mouseHovering=false;var hoveredEntity=null;var lastMouseCanvasX=0;var lastMouseCanvasY=0;var mouseWorldPos=math.vec3();var mouseHoverCanvasPos=math.vec2();this._currentAngleMeasurement=null;this._onMouseHoverSurface=cameraControl.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",function(event){if(event.snappedToVertex||event.snappedToEdge){if(pointerLens){pointerLens.visible=true;pointerLens.canvasPos=event.canvasPos;pointerLens.snappedCanvasPos=event.snappedCanvasPos||event.canvasPos;pointerLens.snapped=true;}_this19.markerDiv.style.background="greenyellow";_this19.markerDiv.style.border="2px solid green";}else{if(pointerLens){pointerLens.visible=true;pointerLens.canvasPos=event.canvasPos;pointerLens.snappedCanvasPos=event.canvasPos;pointerLens.snapped=false;}_this19.markerDiv.style.background="pink";_this19.markerDiv.style.border="2px solid red";}var canvasPos=event.snappedCanvasPos||event.canvasPos;mouseHovering=true;hoveredEntity=event.entity;mouseWorldPos.set(event.worldPos);mouseHoverCanvasPos.set(canvasPos);switch(_this19._mouseState){case MOUSE_FINDING_ORIGIN:var canvasBoundRect=canvas.getBoundingClientRect();var scrollLeft=window.pageXOffset||document.documentElement.scrollLeft;var scrollTop=window.pageYOffset||document.documentElement.scrollTop;var canvasLeftEdge=canvasBoundRect.left+scrollLeft;var canvasTopEdge=canvasBoundRect.top+scrollTop;_this19.markerDiv.style.left="".concat(canvasLeftEdge+canvasPos[0]-5,"px");_this19.markerDiv.style.top="".concat(canvasTopEdge+canvasPos[1]-5,"px");break;case MOUSE_FINDING_CORNER:if(_this19._currentAngleMeasurement){_this19._currentAngleMeasurement.originWireVisible=true;_this19._currentAngleMeasurement.targetWireVisible=false;_this19._currentAngleMeasurement.cornerVisible=true;_this19._currentAngleMeasurement.angleVisible=false;_this19._currentAngleMeasurement.corner.worldPos=event.worldPos;_this19._currentAngleMeasurement.corner.entity=event.entity;}_this19.markerDiv.style.left="-10000px";_this19.markerDiv.style.top="-10000px";canvas.style.cursor="pointer";break;case MOUSE_FINDING_TARGET:if(_this19._currentAngleMeasurement){_this19._currentAngleMeasurement.targetWireVisible=true;_this19._currentAngleMeasurement.targetVisible=true;_this19._currentAngleMeasurement.angleVisible=true;_this19._currentAngleMeasurement.target.worldPos=event.worldPos;_this19._currentAngleMeasurement.target.entity=event.entity;}_this19.markerDiv.style.left="-10000px";_this19.markerDiv.style.top="-10000px";canvas.style.cursor="pointer";break;}});canvas.addEventListener('mousedown',this._onMouseDown=function(e){if(e.which!==1){return;}lastMouseCanvasX=e.clientX;lastMouseCanvasY=e.clientY;});canvas.addEventListener("mouseup",this._onMouseUp=function(e){if(e.which!==1){return;}if(e.clientX>lastMouseCanvasX+clickTolerance||e.clientXlastMouseCanvasY+clickTolerance||e.clientYlastMouseCanvasX+clickTolerance||e.clientXlastMouseCanvasY+clickTolerance||e.clientYpointerDownCanvasX+clickTolerance||e.clientXpointerDownCanvasY+clickTolerance||e.clientYpointerDownCanvasX+clickTolerance||e.clientXpointerDownCanvasY+clickTolerance||e.clientYo,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>c.dotVec4(e,e),lenVec4:e=>Math.sqrt(c.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=>c.dotVec3(e,e),sqLenVec2:e=>c.dotVec2(e,e),lenVec3:e=>Math.sqrt(c.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>c.lenVec3(c.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(c.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>c.lenVec2(c.subVec2(t,i,e))})(),rcpVec3:(e,t)=>c.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/c.lenVec4(e);return c.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/c.lenVec3(e);return c.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/c.lenVec2(e);return c.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=c.dotVec3(e,t)/Math.sqrt(c.sqLenVec3(e)*c.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=c.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=c.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=c.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||c.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:()=>c.m4s(0),setMat4ToOnes:()=>c.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>c.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>c.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>c.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],B=t[3],x=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+B*f,i[1]=v*r+b*l+y*u+B*g,i[2]=v*o+b*A+y*d+B*m,i[3]=v*n+b*h+y*p+B*_,i[4]=x*s+w*a+P*c+C*f,i[5]=x*r+w*l+P*u+C*g,i[6]=x*o+w*A+P*d+C*m,i[7]=x*n+w*h+P*p+C*_,i[8]=M*s+F*a+E*c+I*f,i[9]=M*r+F*l+E*u+I*g,i[10]=M*o+F*A+E*d+I*m,i[11]=M*n+F*h+E*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*g+A*v,i[4]=a*p+l*m+A*b,i[7]=a*f+l*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=c.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,B=s*A-o*a,x=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,F=c*m-d*f,E=u*m-d*g,I=1/(_*E-v*F+b*M+y*C-B*P+x*w);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*x-g*B+m*y)*I,t[3]=(-c*x+u*B-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*x+g*b-m*v)*I,t[7]=(h*x-u*b+d*v)*I,t[8]=(n*F-a*C+A*w)*I,t[9]=(-i*F+s*C-o*w)*I,t[10]=(p*B-f*b+m*_)*I,t[11]=(-h*B+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||c.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||c.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.translationMat4v(e,r))})(),translationMat4s:(e,t)=>c.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>c.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=c.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,u,d,p,f,g;return h=a*l,u=l*A,d=A*a,p=a*r,f=l*r,g=A*r,(i=i||c.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*d-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>c.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=c.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=c.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>c.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=c.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,u=s*l,d=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=d+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=c.vec4()){const s=c.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-h,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i},composeMat4:(e,t,i,s=c.mat4())=>(c.quaternionToRotationMat4(t,s),c.scaleMat4v(i,s),c.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=c.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=c.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=c.lenVec3(e);c.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=u,t[9]*=u,t[10]*=u,c.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=c.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],u=t[1],d=t[2];if(r===h&&o===u&&n===d)return c.identityMat4();let p,f,g,m,_,v,b,y,B,x;return p=r-h,f=o-u,g=n-d,x=1/Math.sqrt(p*p+f*f+g*g),p*=x,f*=x,g*=x,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,x=Math.sqrt(m*m+_*_+v*v),x?(x=1/x,m*=x,_*=x,v*=x):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,B=p*_-f*m,x=Math.sqrt(b*b+y*y+B*B),x?(x=1/x,b*=x,y*=x,B*=x):(b=0,y=0,B=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=B,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+B*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>c.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=c.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];c.addVec4(r,s,l),c.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],h=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/h,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/h,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],c.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=c.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],B=e[13],x=e[14],w=e[15];let P;for(let e=0;e{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||c.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||c.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=c.vec4()){const s=e[0]*c.DEGTORAD/2,r=e[1]*c.DEGTORAD/2,o=e[2]*c.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"YXZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"ZXY"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"ZYX"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"YZX"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l-A*h*u):"XZY"===t&&(i[0]=A*a*l-n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l+A*h*u),i},mat4ToQuaternion(e,t=c.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let u;const d=i+n+h;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>h?(u=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>h?(u=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=c.vec4()){const s=Math.sqrt(c.dotVec3(e,e)*c.dotVec3(t,t));let r=s+c.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):c.cross3Vec3(e,t,i),i[3]=r,c.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=c.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||c.vec3(),c.quaternionToRotationMat4(t,e),c.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=c.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-h*-l,i[2]=d*A+p*-l+h*-a-u*-n,i},quaternionToMat4(e,t){t=c.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,u=l*o,d=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+u,t[2]=f-h,t[4]=p-u,t[5]=1-(d+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(d+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=c.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>c.normalizeQuaternion(c.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=c.vec4()){const i=(e=c.normalizeQuaternion(e,h))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],B=e[14],x=e[15];for(s=0;s{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],c.subVec3(t,e,i),Math.abs(c.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=c.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>u?h:u,Math.abs(c.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||c.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||c.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=c.AABB3())=>(e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MAX_DOUBLE,e[3]=c.MIN_DOUBLE,e[4]=c.MIN_DOUBLE,e[5]=c.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=c.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new n(3);return(t,i,s)=>{i=i||c.AABB3();let r,o,n,a=c.MAX_DOUBLE,l=c.MAX_DOUBLE,A=c.MAX_DOUBLE,h=c.MIN_DOUBLE,u=c.MIN_DOUBLE,d=c.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||c.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;ru&&(u=h);return s[3]=u,s}})(),getSphere3Center:(e,t=c.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=c.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MIN_DOUBLE,e[3]=c.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=c.AABB2()){let i,s,r,o,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=c.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(h*h+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,h)=>{h=h||c.vec3();const u=c.subVec3(l,a,e),d=c.subVec3(A,a,t),p=c.cross3Vec3(n,d,i),f=c.dotVec3(u,p);if(f<1e-6)return null;const g=c.subVec3(o,a,s),m=c.dotVec3(g,p);if(m<0||m>f)return null;const _=c.cross3Vec3(g,u,r),v=c.dotVec3(n,_);if(v<0||m+v>f)return null;const b=c.dotVec3(d,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||c.vec3(),o=c.normalizeVec3(o,e);const h=c.subVec3(a,n,t),u=c.subVec3(l,n,i),d=c.cross3Vec3(h,u,s);c.normalizeVec3(d,d);const p=-c.dotVec3(n,d),f=-(c.dotVec3(r,d)+p)/c.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=c.subVec3(n,r,e),A=c.subVec3(o,r,t),h=c.subVec3(s,r,i),u=c.dotVec3(l,l),d=c.dotVec3(l,A),p=c.dotVec3(l,h),f=c.dotVec3(A,A),g=c.dotVec3(A,h),m=u*f-d*d;if(0===m)return null;const _=1/m,v=(f*p-d*g)*_,b=(u*g-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=c.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,h;const u=new Array(n.length/3);let d,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const h=new Float32Array(n.length);for(let u=0;u>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,u;const d=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,c.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],c.transformVec3(i,e,t),c.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(16),i=new n(4),s=new n(4),r=new n(4),o=new n(4);return(n,a,l,A,h,u)=>{const d=c.mulMat4(l,a,e),p=c.inverseMat4(d,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,c.transformVec4(p,i,s),c.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,c.transformVec4(p,r,o),c.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],c.subVec3(o,s,u),c.normalizeVec3(u)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l)=>{c.canvasPosToWorldRay(i,s,r,n,e,t),c.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=c.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],c.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;Aa[3]&&(a[3]=r[t]),r[t+1]a[4]&&(a[4]=r[t+1]),r[t+2]a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};c.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),c.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:m,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s0&&w>0){var t=1e3/w;C+=t,x.push(t),x.length>=30&&(C-=x.shift()),p.frame.fps=Math.round(C/x.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{F()}),100);const E=function(){let e=Date.now();if(w=e-P,P>0&&w>0){var t=1e3/w;C+=t,x.push(t),x.length>=30&&(C-=x.shift()),p.frame.fps=Math.round(C/x.length)}I(e),function(e){for(var t in B.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];B.sceneId=t,B.startTime=i.startTime,B.deltaTime=null!=B.prevTime?B.time-B.prevTime:0,i.fire("tick",B,!0)}B.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(F):requestAnimationFrame(E)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}E();class D{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 D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class U{constructor(){this.planes=[new L,new L,new L,new L,new L,new L]}}function O(e,t,i){const s=c.mulMat4(i,t,R),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],u=s[7],d=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,g-d,b-m),e.planes[1].set(a+r,u+l,g+d,b+m),e.planes[2].set(a-o,u-A,g-p,b-_),e.planes[3].set(a+o,u+A,g+p,b+_),e.planes[4].set(a-n,u-h,g-f,b-v),e.planes[5].set(a+n,u+h,g+f,b+v)}function k(e,t){let i=U.INSIDE;const s=S,r=T;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return U.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=U.INTERSECT)}return i}U.INSIDE=0,U.INTERSECT=1,U.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=c.vec2(),this._canvasMarqueeCorner2=c.vec2(),this._canvasMarquee=c.AABB2(),this._marqueeFrustum=new U,this._marqueeFrustumProjMat=c.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=U.INTERSECT)=>{if(s===U.INTERSECT&&(s=k(this._marqueeFrustum,i.aabb)),s!==U.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);c.frustumMat4(l,A,h*a,u*a,d,1e4,this._marqueeFrustumProjMat),O(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class Q{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const H=c.vec3(),V=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(s,t,i),c.setMat4Translation(s,i,o),o.slice()}}();function j(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function G(e,t,i,s=1e3){const r=c.getPositionsCenter(e,H),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{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&&(c.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){re.set(this._viewPos),re[3]=1,c.transformPoint4(this.scene.camera.projMatrix,re,oe);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+oe[0]/oe[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-oe[1]/oe[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 se?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),j(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class ae{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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,i=this._wire.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)";var s=this._wireClickable.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)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class le{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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 i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class Ae{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 i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-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 he=c.vec3(),ce=c.vec3();class ue extends D{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 i=this.plugin.viewer.scene;this._originMarker=new ne(i,t.origin),this._cornerMarker=new ne(i,t.corner),this._targetMarker=new ne(i,t.target),this._originWorld=c.vec3(),this._cornerWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ae(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ae(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new Ae(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),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=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const d=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>d||f>d||g>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);c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,u=t.length;h{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:const s=t.getBoundingClientRect(),r=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,n=s.left+r,a=s.top+o;this.markerDiv.style.left=n+i[0]-5+"px",this.markerDiv.style.top=a+i[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class fe extends ne{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||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[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 i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}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 i=e[t];this.setField(t,i)}}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 ge=c.vec3(),me=c.vec3(),_e=c.vec3();class ve extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const be=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class ye extends D{constructor(e,t={}){super(e,t),this._backgroundColor=c.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new 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-"+c.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?xe.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?xe.FS_MAX_FLOAT_PRECISION="mediump":xe.FS_MAX_FLOAT_PRECISION="lowp":xe.FS_MAX_FLOAT_PRECISION="mediump",xe.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),xe.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),xe.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),xe.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),xe.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),xe.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),xe.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),xe.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),xe.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),xe.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){xe.SUPPORTED_EXTENSIONS[e]=!0})))}class Pe{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Ce{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function De(e){console.error(e.join("\n"))}class Se{constructor(e,t){this.id=Ee.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 Ce(e,e.VERTEX_SHADER,Ie(this.source.vertex)),this._fragmentShader=new Ce(e,e.FRAGMENT_SHADER,Ie(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void De(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void De(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void De(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void De(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void De(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.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 Re{constructor(e,t){this.scene=e,this.aabb=c.AABB3(),this.origin=c.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-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new Re(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new Re(this._scene,e.origin),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Se(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;ke[0]=o,ke[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,ke),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Se(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Te(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Te(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Te(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Qe=new Float32Array(Ke(17,[0,1])),He=new Float32Array(Ke(17,[1,0])),Ve=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(ze(s,t));return i}(17,4)),je=new Float32Array(2);class Ge{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]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Te(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Te(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Te(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),je[0]=n,je[1]=a,s.uniform2fv(this._uViewport,je),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,He):s.uniform2fv(this._uSampleOffsets,Qe),s.uniform1fv(this._uSampleWeights,Ve);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function ze(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Ke(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class We{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class Xe{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new We(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Je(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const Ye=function(t,i){i=i||{};const s=new Be(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},u=!0,d=!0,f=!0,g=!0,m=!0,_=!0,v=!0,b=!0;const y=new Xe(t);let B=!1;const x=new Ne(t),w=new Ge(t);function P(){u&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),u=!1,d=!0),d&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,f=!0),f&&function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||j>0||k>0||N>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||N>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),N>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||z>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),z>0)for(S=0;S0)for(S=0;S0||W>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||J>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),J>0)for(S=0;S0)for(S=0;S0||Z>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Z>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=d.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let D=null,S=null,T=null,R=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),R=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;S=c.normalizeVec3([t[0]/c.MAX_INT,t[1]/c.MAX_INT,t[2]/c.MAX_INT]),D=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===B&&null==D)return null;let L=null;null!==D&&(L=t.camera.projectWorldPos(D));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===R,h.snappedToVertex="vertex"===R,h.worldPos=D,h.worldNormal=S,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=L||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Oe(t,y),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const qe=new e({});class $e{constructor(e){this.id=qe.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){qe.removeItem(this.id)}}class et extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new $e({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class tt extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),c.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class it extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),c.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class st extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.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(){c.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&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class rt extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.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&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ot=c.vec3(),nt=c.vec3(),at=c.vec3(),lt=c.vec3(),At=c.vec3(),ht=c.vec3(),ct=c.vec4(),ut=c.vec4(),dt=c.vec4(),pt=c.mat4(),ft=c.mat4(),gt=c.vec3(),mt=c.vec3(),_t=c.vec3(),vt=c.vec3();class bt extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new $e({deviceMatrix:c.mat4(),hasDeviceMatrix:!1,matrix:c.mat4(),normalMatrix:c.mat4(),inverseMatrix:c.mat4()}),this._perspective=new tt(this),this._ortho=new it(this),this._frustum=new st(this),this._customProjection=new rt(this),this._project=this._perspective,this._eye=c.vec3([0,0,10]),this._look=c.vec3([0,0,0]),this._up=c.vec3([0,1,0]),this._worldUp=c.vec3([0,1,0]),this._worldRight=c.vec3([1,0,0]),this._worldForward=c.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?(c.subVec3(this._eye,this._look,gt),c.normalizeVec3(gt,mt),c.mulVec3Scalar(mt,1e3,_t),c.addVec3(this._look,_t,vt),t=vt):t=this._eye,e.hasDeviceMatrix?(c.lookAtMat4v(t,this._look,this._up,ft),c.mulMat4(e.deviceMatrix,ft,e.matrix)):c.lookAtMat4v(t,this._look,this._up,e.matrix),c.inverseMat4(this._state.matrix,this._state.inverseMatrix),c.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=c.subVec3(this._eye,this._look,ot);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=c.transformPoint3(pt,t,nt),this.eye=c.addVec3(this._look,t,at),this.up=c.transformPoint3(pt,this._up,lt)}orbitPitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._eye,this._look,ot);const i=c.cross3Vec3(c.normalizeVec3(t,nt),c.normalizeVec3(this._up,at));c.rotationMat4v(.0174532925*e,i,pt),t=c.transformPoint3(pt,t,lt),this.up=c.transformPoint3(pt,this._up,At),this.eye=c.addVec3(t,this._look,ht)}yaw(e){let t=c.subVec3(this._look,this._eye,ot);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=c.transformPoint3(pt,t,nt),this.look=c.addVec3(t,this._eye,at),this._gimbalLock&&(this.up=c.transformPoint3(pt,this._up,lt))}pitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._look,this._eye,ot);const i=c.cross3Vec3(c.normalizeVec3(t,nt),c.normalizeVec3(this._up,at));c.rotationMat4v(.0174532925*e,i,pt),this.up=c.transformPoint3(pt,this._up,ht),t=c.transformPoint3(pt,t,lt),this.look=c.addVec3(t,this._eye,At)}pan(e){const t=c.subVec3(this._eye,this._look,ot),i=[0,0,0];let s;if(0!==e[0]){const r=c.cross3Vec3(c.normalizeVec3(t,[]),c.normalizeVec3(this._up,nt));s=c.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=c.mulVec3Scalar(c.normalizeVec3(this._up,at),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=c.mulVec3Scalar(c.normalizeVec3(t,lt),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=c.addVec3(this._eye,i,At),this.look=c.addVec3(this._look,i,ht)}zoom(e){const t=c.subVec3(this._eye,this._look,ot),i=Math.abs(c.lenVec3(t,nt)),s=Math.abs(i+e);if(s<.5)return;const r=c.normalizeVec3(t,at);this.eye=c.addVec3(this._look,c.mulVec3Scalar(r,s),lt)}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=c.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 c.lenVec3(c.subVec3(this._look,this._eye,ot))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=ct,i=ut,s=dt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,c.mulMat4v4(this.viewMatrix,t,i),c.mulMat4v4(this.projMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class yt extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Bt extends yt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new $e({type:"dir",dir:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=c.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];c.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=c.identityMat4()),c.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new We(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class xt extends yt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:c.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class wt extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var Pt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const Ct=function(){const e=c.mat4(),t=c.mat4();return function(i,s){s=s||c.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return c.identityMat4(e),c.translationMat4v(i,e),c.identityMat4(t),c.scalingMat4v([a/h,l/h,A/h],t),c.mulMat4(e,t,s),s}}();var Mt=function(){const e=c.mat4(),t=c.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function It(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Dt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const St={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Et(e,a,"floor","ceil"),s=It(i),o=Dt(e,a,s),o>n&&(r=i,n=o),i=Et(e,a,"ceil","ceil"),s=It(i),o=Dt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Tt=p.memory,Rt=c.AABB3();class Lt extends wt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new $e({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=St.getPositionsBounds(t.positions),s=St.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=St.getUVBounds(t.uv),s=St.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=St.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Tt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Tt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Te(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Tt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new Te(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Tt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Te(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Tt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Te(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Tt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=Pt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Tt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=c.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Te(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Tt.positions+=this._pickTrianglePositionsBuf.numItems,Tt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),St.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=St.getPositionsBounds(e),s=St.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),St.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),St.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=c.AABB3()),c.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=c.OBB3()),c.positions3ToAABB3(this._state.positions,Rt,this._state.positionsDecodeMatrix),c.AABB3ToOBB3(Rt,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Tt.meshes--}}function Ut(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Ot extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const kt={opaque:0,mask:1,blend:2},Nt=["opaque","mask","blend"];class Qt extends Ot{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new $e({type:"PhongMaterial",ambient:c.vec3([1,1,1]),diffuse:c.vec3([1,1,1]),specular:c.vec3([1,1,1]),emissive:c.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=kt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Nt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Ht={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Vt extends Ot{get type(){return"EmphasisMaterial"}get presets(){return Ht}constructor(e,t={}){super(e,t),this._state=new $e({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Ht[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ht).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const jt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Gt extends Ot{get type(){return"EdgeMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new $e({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=jt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(jt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const zt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Kt extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=c.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return zt}set units(e){e||(e="meters");zt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=c.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=c.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class Wt extends D{constructor(e,t={}){super(e,t),this._supported=xe.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const Xt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Jt extends Ot{get type(){return"PointsMaterial"}get presets(){return Xt}constructor(e,t={}){super(e,t),this._state=new $e({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=Xt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Xt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Zt extends Ot{get type(){return"LinesMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new $e({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function qt(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Ye(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=c.vec4([0,0,0,0]),t=c.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+_.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=c.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],_.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=qt(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=qt(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=c.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ei=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=si(e),u=s.getNumAllocatedSectionPlanes()>0,d=ii(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=si(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=ii(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+ti[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+ti[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ti[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ti[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ti[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ti[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class li{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ai=new e({}),hi=c.vec3(),ci=function(e,t){this.id=Ai.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new li(t),this._allocate(t)},ui={};ci.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ui[t];return i||(i=new ci(t,e),ui[t]=i,p.memory.programs++),i._useCount++,i},ci.prototype.put=function(){0==--this._useCount&&(Ai.removeItem(this.id),this._program&&this._program.destroy(),delete ui[this._hash],p.memory.programs--)},ci.prototype.webglContextRestored=function(){this._program=null},ci.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const pi=new e({}),fi=c.vec3(),gi=function(e,t){this.id=pi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new di(t),this._allocate(t)},mi={};gi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=mi[t];return i||(i=new gi(t,e),mi[t]=i,p.memory.programs++),i._useCount++,i},gi.prototype.put=function(){0==--this._useCount&&(pi.removeItem(this.id),this._program&&this._program.destroy(),delete mi[this._hash],p.memory.programs--)},gi.prototype.webglContextRestored=function(){this._program=null},gi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const vi=c.vec3(),bi=function(e,t){this._hash=e,this._shaderSource=new _i(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},yi={};bi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=yi[t];if(!i){if(i=new bi(t,e),i.errors)return console.log(i.errors.join("\n")),null;yi[t]=i,p.memory.programs++}return i._useCount++,i},bi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete yi[this._hash],p.memory.programs--)},bi.prototype.webglContextRestored=function(){this._program=null},bi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},bi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Se(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const xi=c.vec3(),wi=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Bi(t),this._allocate(t)},Pi={};wi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Pi[t];if(!i){if(i=new wi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Pi[t]=i,p.memory.programs++}return i._useCount++,i},wi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Pi[this._hash],p.memory.programs--)},wi.prototype.webglContextRestored=function(){this._program=null},wi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Mi=c.vec3(),Fi=function(e,t){this._hash=e,this._shaderSource=new Ci(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ei={};Fi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ei[t];if(!i){if(i=new Fi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ei[t]=i,p.memory.programs++}return i._useCount++,i},Fi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ei[this._hash],p.memory.programs--)},Fi.prototype.webglContextRestored=function(){this._program=null},Fi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Di=function(e,t){this._hash=e,this._shaderSource=new Ii(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Si={};Di.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Si[i];if(!s){if(s=new Di(i,e),s.errors)return console.log(s.errors.join("\n")),null;Si[i]=s,p.memory.programs++}return s._useCount++,s},Di.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Si[this._hash],p.memory.programs--)},Di.prototype.webglContextRestored=function(){this._program=null},Di.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Di.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Se(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const zi=function(){const e=c.vec3(),t=c.vec3(),i=c.vec3(),s=c.vec3(),r=c.vec3(),o=c.vec3(),n=c.vec4(),a=c.vec3(),l=c.vec3(),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3(),m=c.vec4(),_=c.vec4(),v=c.vec4(),b=c.vec3(),y=c.vec3(),B=c.vec3(),x=c.vec3(),w=c.vec3(),P=c.vec3(),C=c.vec3(),M=c.vec3(),F=c.vec3(),E=c.vec3(),I=c.vec3();return function(D,S,T,R){var L=R.primIndex;if(null!=L&&L>-1){const N=D.geometry._state,Q=D.scene,H=Q.camera,j=Q.canvas;if("triangles"===N.primitiveName){R.primitive="triangle";const Q=L,G=N.indices,z=N.positions;let K,W,X;if(G){var U=G[Q+0],O=G[Q+1],k=G[Q+2];o[0]=U,o[1]=O,o[2]=k,R.indices=o,K=3*U,W=3*O,X=3*k}else K=3*Q,W=K+3,X=W+3;if(i[0]=z[K+0],i[1]=z[K+1],i[2]=z[K+2],s[0]=z[W+0],s[1]=z[W+1],s[2]=z[W+2],r[0]=z[X+0],r[1]=z[X+1],r[2]=z[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(St.decompressPosition(i,e,i),St.decompressPosition(s,e,s),St.decompressPosition(r,e,r))}R.canvasPos?c.canvasPosToLocalRay(j.canvas,D.origin?V(S,D.origin):S,T,D.worldMatrix,R.canvasPos,e,t):R.origin&&R.direction&&c.worldRayToLocalRay(D.worldMatrix,R.origin,R.direction,e,t),c.normalizeVec3(t),c.rayPlaneIntersect(e,t,i,s,r,n),R.localPos=n,R.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,c.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],R.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),R.worldPos=a,c.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],R.viewPos=l,c.cartesianToBarycentric(n,i,s,r,A),R.bary=A;const J=N.normals;if(J){if(N.compressGeometry){const e=3*U,t=3*O,i=3*k;St.decompressNormal(J.subarray(e,e+2),h),St.decompressNormal(J.subarray(t,t+2),u),St.decompressNormal(J.subarray(i,i+2),d)}else h[0]=J[K],h[1]=J[K+1],h[2]=J[K+2],u[0]=J[W],u[1]=J[W+1],u[2]=J[W+2],d[0]=J[X],d[1]=J[X+1],d[2]=J[X+2];const e=c.addVec3(c.addVec3(c.mulVec3Scalar(h,A[0],b),c.mulVec3Scalar(u,A[1],y),B),c.mulVec3Scalar(d,A[2],x),w);R.worldNormal=c.normalizeVec3(c.transformVec3(D.worldNormalMatrix,e,P))}const Y=N.uv;if(Y){if(p[0]=Y[2*U],p[1]=Y[2*U+1],f[0]=Y[2*O],f[1]=Y[2*O+1],g[0]=Y[2*k],g[1]=Y[2*k+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(St.decompressUV(p,e,p),St.decompressUV(f,e,f),St.decompressUV(g,e,g))}R.uv=c.addVec3(c.addVec3(c.mulVec2Scalar(p,A[0],C),c.mulVec2Scalar(f,A[1],M),F),c.mulVec2Scalar(g,A[2],E),I)}}}}}();function Ki(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],v=[],b=[];let y,B,x,w,P,C,M,F,E,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=c-y*u,B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),m.push(P*x),m.push(S),m.push(P*w),v.push(B*p),v.push(1*y/o),g.push(P*x+l),g.push(C+A),g.push(P*w+h);for(y=0;y0){for(E=g.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(t*x),m.push(1),m.push(t*w),v.push(I),v.push(D),g.push(t*x+l),g.push(c+A),g.push(t*w+h);for(B=0;B0){for(E=g.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(i*x),m.push(-1),m.push(i*w),v.push(I),v.push(D),g.push(i*x+l),g.push(0-c+A),g.push(i*w+h);for(B=0;B":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Ji(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,v=(l||"").split("\n"),b=0,y=0,B=.04,x=0;x0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=ps(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ps(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ps(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,_s(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,_s(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ps(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ps(i,this.magFilter)));const a=ps(i,this.format,this.encoding),l=ps(i,this.type),A=ms(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Bs extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new $e({texture:new gs({gl:this.scene.canvas.gl}),matrix:c.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=c.vec2([0,0]),this._scale=c.vec2([1,1]),this._rotate=c.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),p.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new gs({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=c.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=c.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?c.mulMat4(t,i):i),0!==this._rotate&&(i=c.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?c.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=vs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=vs(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const xs=p.memory,ws=c.AABB3();class Ps extends wt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new $e({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=c.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=St.getPositionsBounds(t.positions),o=St.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new Te(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),xs.positions+=i.positionsBuf.numItems,c.positions3ToAABB3(t.positions,this._aabb),c.positions3ToAABB3(r,ws,i.positionsDecodeMatrix),c.AABB3ToOBB3(ws,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new Te(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),xs.colors+=i.colorsBuf.numItems}if(t.uv){const e=St.getUVBounds(t.uv),r=St.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new Te(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),xs.uvs+=i.uvBuf.numItems}if(t.normals){const e=St.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new Te(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),xs.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),xs.indices+=i.indicesBuf.numItems;const o=Pt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),xs.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),xs.meshes--}}var Cs={};function Ms(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Fs(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Es(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,B,x,w,P,C,M,F=0,E=0;for(y=0;y65535?Uint32Array:Uint16Array)(c*u*6);for(y=0;y360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],u=[],d=[],p=[];let f,g,m,v,b,y,B,x,w,P,C,M;for(x=0;x<=r;x++)for(B=0;B<=s;B++)f=B/s*o,g=.785398+x/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),v=(t+i*Math.cos(g))*Math.sin(f),b=i*Math.sin(g),h.push(m+a),h.push(v+l),h.push(b+A),d.push(1-B/s),d.push(x/r),y=c.normalizeVec3(c.subVec3([m,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(x=1;x<=r;x++)for(B=1;B<=s;B++)w=(s+1)*x+B-1,P=(s+1)*(x-1)+B-1,C=(s+1)*(x-1)+B,M=(s+1)*x+B,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return _.apply(e,{positions:h,normals:u,uv:d,indices:p})}function Ds(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e>8},Cs.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Cs.parse={},Cs.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Ss extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=c.vec3(t.pos||[0,0,0]),this._up=c.vec3(t.up||[0,1,0]),this._normal=c.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=c.vec3(),this._rtcPos=c.vec3(),this._imageSize=c.vec2(),this._texture=new Bs(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new ns(this,{matrix:c.inverseMat4(c.lookAtMat4v(this._pos,c.subVec3(this._pos,this._normal,c.mat4()),this._up,c.mat4())),children:[this._bitmapMesh=new Gi(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Lt(this,Es({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Qt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const Ts=c.OBB3(),Rs=c.OBB3(),Ls=c.OBB3();class Us{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=c.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(c.AABB3ToOBB3(this._aabbLocal,Ts),this.transform?(c.transformOBB3(this.transform.worldMatrix,Ts,Rs),c.transformOBB3(this.model.worldMatrix,Rs,Ls),c.OBB3ToAABB3(Ls,this._aabbWorld)):(c.transformOBB3(this.model.worldMatrix,Ts,Rs),c.OBB3ToAABB3(Rs,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const Os=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let ks=0;const Ns={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Qs=new Float32Array([1,1,1,1]),Hs=new Float32Array([0,0,0,1]),Vs=c.vec4(),js=c.vec3(),Gs=c.vec3(),zs=c.mat4();class Ks{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;Vs[0]=i,Vs[1]=s,Vs[2]=t.blendCutoff,Vs[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Vs),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Ns[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ns[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ns[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?Hs:Qs)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class Ws extends Ks{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Xs extends Ws{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class Js extends Ws{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = vColor;"),o.push("}"),o}}class Zs extends Ws{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class qs extends Zs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class $s extends Zs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class er extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class tr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ir extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class sr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class rr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class or extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class nr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class ar extends Ws{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Ar extends Ws{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gr=c.vec3(),mr=c.vec3(),_r=c.vec3(),vr=c.vec3(),br=c.mat4();class yr extends Ks{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=gr;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=mr;if(l){const e=_r;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,br),m=vr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Br{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ys(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new er(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new tr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new fr(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new yr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Xs(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Xs(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Js(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Js(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ar(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ar(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ar(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ar(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ys(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new rr(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new or(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new qs(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new $s(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new er(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ir(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new lr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new tr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new sr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new nr(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new yr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new fr(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const xr={};let wr=65536,Pr=5e6;class Cr{constructor(){}set doublePrecisionEnabled(e){c.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return c.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),wr=e}get maxDataTextureHeight(){return wr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Pr=e}get maxGeometryBatchSize(){return Pr}}const Mr=new Cr;class Fr{constructor(){this.maxVerts=Mr.maxGeometryBatchSize,this.maxIndices=3*Mr.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Er=c.mat4(),Ir=c.mat4();function Dr(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,u=65525,d=u/l,p=u/A,f=u/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function Rr(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Lr=c.mat4(),Ur=c.mat4(),Or=c.vec4([0,0,0,1]),kr=c.vec3(),Nr=c.vec3(),Qr=c.vec3(),Hr=c.vec3(),Vr=c.vec3(),jr=c.vec3(),Gr=c.vec3();class zr{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=xr[t];return i||(i=new Br(e),xr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete xr[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Fr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new $e({origin:c.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=c.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=c.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Lr;m?c.inverseMat4(c.transposeMat4(m,Ur),e):c.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;uh&&(l=n,h=A),n=Tr(p,"floor","ceil"),a=Rr(n),A=o(p,a),A>h&&(l=n,h=A),n=Tr(p,"ceil","ceil"),a=Rr(n),A=o(p,a),A>h&&(l=n,h=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Dr(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=c.mat4());if(e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new Te(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new Te(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=St.getUVBounds(i.uv),r=St.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=c.mat3(r.decodeMatrix),e.uvBuf=new Te(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Te(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Te(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&c.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Kr extends Ks{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Wr extends Kr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class Xr extends Kr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Yr extends Kr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Zr extends Yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class qr extends Yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class $r extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class eo extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class to extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class io extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class so extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class ro extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class oo extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const no={3e3:"linearToLinear",3001:"sRGBToLinear"};class ao extends Kr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+no[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+no[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Ao extends Kr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const mo=c.vec3(),_o=c.vec3(),vo=c.vec3(),bo=c.vec3(),yo=c.mat4();class Bo extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=mo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=_o;if(l){const e=c.transformPoint3(h,l,vo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,yo),m=bo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class xo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Jr(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new $r(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new eo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new go(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Bo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Wr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Xr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Xr(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ao(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ao(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ao(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ao(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new so(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ro(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Zr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new qr(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new $r(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new to(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new lo(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new eo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new io(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new oo(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new go(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Bo(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const wo={};const Po=new Uint8Array(4),Co=new Float32Array(1),Mo=c.vec4([0,0,0,1]),Fo=new Float32Array(3),Eo=c.vec3(),Io=c.vec3(),Do=c.vec3(),So=c.vec3(),To=c.vec3(),Ro=c.vec3(),Lo=c.vec3(),Uo=new Float32Array(4);class Oo{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=wo[t];return i||(i=new xo(e),wo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete wo[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new $e({numInstances:0,obb:c.OBB3(),origin:c.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Te(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Te(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new Te(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new Te(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=c.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Te(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Te(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Te(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Po[0]=t[0],Po[1]=t[1],Po[2]=t[2],Po[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Po,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&Z),o=!!(t&q),n=!!(t&$),a=!!(t&ee),l=!!(t&X),A=!!(t&W);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ns.NOT_RENDERED:i?Ns.COLOR_TRANSPARENT:Ns.COLOR_OPAQUE,c=!s||A?Ns.NOT_RENDERED:n?Ns.SILHOUETTE_SELECTED:o?Ns.SILHOUETTE_HIGHLIGHTED:r?Ns.SILHOUETTE_XRAYED:Ns.NOT_RENDERED;let u=0;u=!s||A?Ns.NOT_RENDERED:n?Ns.EDGES_SELECTED:o?Ns.EDGES_HIGHLIGHTED:r?Ns.EDGES_XRAYED:a?i?Ns.EDGES_COLOR_TRANSPARENT:Ns.EDGES_COLOR_OPAQUE:Ns.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ns.PICK:Ns.NOT_RENDERED)<<12,d|=(t&J?1:0)<<16,Co[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Co,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Fo[0]=t[0],Fo[1]=t[1],Fo[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Fo,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],u=Mo,d=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&c.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(c.transformVec3(a.normalMatrix,r,r),c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ko extends Ks{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class No extends ko{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Qo extends ko{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Ho=c.vec3(),Vo=c.vec3(),jo=c.vec3(),Go=c.vec3(),zo=c.mat4();class Ko extends Ks{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ho;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Vo;if(l){const e=jo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,zo),m=Go,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Wo=c.vec3(),Xo=c.vec3(),Jo=c.vec3(),Yo=c.vec3(),Zo=c.mat4();class qo extends Ks{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Wo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Xo;if(l){const e=Jo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,Zo),m=Yo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class $o{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new No(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Qo(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ko(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new qo(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const en={};class tn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class sn{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=en[t];return i||(i=new $o(e),en[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete en[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new tn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new $e({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Dr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Te(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class nn extends rn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const an=c.vec3(),ln=c.vec3(),An=c.vec3();c.vec3();const hn=c.mat4();class cn extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=an;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ln;if(l){const e=c.transformPoint3(h,l,An);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,hn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const un=c.vec3(),dn=c.vec3(),pn=c.vec3();c.vec3();const fn=c.mat4();class gn extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=un;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=dn;if(l){const e=c.transformPoint3(h,l,pn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,fn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class mn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new cn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new gn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new on(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new nn(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new cn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new gn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const _n={};const vn=new Uint8Array(4),bn=new Float32Array(1),yn=new Float32Array(3),Bn=new Float32Array(4);class xn{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=_n[t];return i||(i=new mn(e),_n[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete _n[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new $e({obb:c.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=c.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Te(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new Te(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new Te(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=c.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Te(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";vn[0]=t[0],vn[1]=t[1],vn[2]=t[2],vn[3]=t[3],this._state.colorsBuf.setData(vn,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&Z),o=!!(t&q),n=!!(t&$),a=!!(t&ee),l=!!(t&X),A=!!(t&W);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ns.NOT_RENDERED:i?Ns.COLOR_TRANSPARENT:Ns.COLOR_OPAQUE,c=!s||A?Ns.NOT_RENDERED:n?Ns.SILHOUETTE_SELECTED:o?Ns.SILHOUETTE_HIGHLIGHTED:r?Ns.SILHOUETTE_XRAYED:Ns.NOT_RENDERED;let u=0;u=!s||A?Ns.NOT_RENDERED:n?Ns.EDGES_SELECTED:o?Ns.EDGES_HIGHLIGHTED:r?Ns.EDGES_XRAYED:a?i?Ns.EDGES_COLOR_TRANSPARENT:Ns.EDGES_COLOR_OPAQUE:Ns.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ns.PICK:Ns.NOT_RENDERED)<<12,d|=(t&J?255:0)<<16,bn[0]=d,this._state.flagsBuf.setData(bn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(yn[0]=t[0],yn[1]=t[1],yn[2]=t[2],this._state.offsetsBuf.setData(yn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Bn[0]=t[0],Bn[1]=t[4],Bn[2]=t[8],Bn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Bn,i),Bn[0]=t[1],Bn[1]=t[5],Bn[2]=t[9],Bn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Bn,i),Bn[0]=t[2],Bn[1]=t[6],Bn[2]=t[10],Bn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Bn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ns.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ns.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class wn extends Ks{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Pn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Cn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class Mn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Fn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class En extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const In=c.vec3(),Dn=c.vec3(),Sn=c.vec3(),Tn=c.vec3(),Rn=c.mat4();class Ln extends Ks{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=In;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Dn;if(l){const e=Sn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,Rn),m=Tn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Un=c.vec3(),On=c.vec3(),kn=c.vec3(),Nn=c.vec3(),Qn=c.mat4();class Hn extends Ks{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Un;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=On;if(l){const e=kn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,Qn),m=Nn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Vn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Pn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Cn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Mn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Fn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new En(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ln(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Hn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const jn={};class Gn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class zn{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=jn[t];return i||(i=new Vn(e),jn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete jn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Gn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new $e({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Dr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Te(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Xn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Jn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Yn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Zn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class qn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class $n extends Kn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const ea=c.vec3(),ta=c.vec3(),ia=c.vec3();c.vec3();const sa=c.mat4();class ra extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ea;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ta;if(l){const e=c.transformPoint3(h,l,ia);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,sa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const oa=c.vec3(),na=c.vec3(),aa=c.vec3();c.vec3();const la=c.mat4();class Aa extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=oa;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=na;if(l){const e=c.transformPoint3(h,l,aa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,la),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ha{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Xn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new qn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Jn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Zn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new $n(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ra(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Aa(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const ca={};const ua=new Uint8Array(4),da=new Float32Array(1),pa=new Float32Array(3),fa=new Float32Array(4);class ga{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=ca[t];return i||(i=new ha(e),ca[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete ca[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new $e({obb:c.OBB3(),numInstances:0,origin:e.origin?c.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new Te(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=c.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new Te(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new Te(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";ua[0]=t[0],ua[1]=t[1],ua[2]=t[2],this._state.colorsBuf.setData(ua,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&Z),o=!!(t&q),n=!!(t&$),a=!!(t&ee),l=!!(t&X),A=!!(t&W);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ns.NOT_RENDERED:i?Ns.COLOR_TRANSPARENT:Ns.COLOR_OPAQUE,c=!s||A?Ns.NOT_RENDERED:n?Ns.SILHOUETTE_SELECTED:o?Ns.SILHOUETTE_HIGHLIGHTED:r?Ns.SILHOUETTE_XRAYED:Ns.NOT_RENDERED;let u=0;u=!s||A?Ns.NOT_RENDERED:n?Ns.EDGES_SELECTED:o?Ns.EDGES_HIGHLIGHTED:r?Ns.EDGES_XRAYED:a?i?Ns.EDGES_COLOR_TRANSPARENT:Ns.EDGES_COLOR_OPAQUE:Ns.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ns.PICK:Ns.NOT_RENDERED)<<12,d|=(t&J?255:0)<<16,da[0]=d,this._state.flagsBuf.setData(da,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(pa[0]=t[0],pa[1]=t[1],pa[2]=t[2],this._state.offsetsBuf.setData(pa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;fa[0]=t[0],fa[1]=t[4],fa[2]=t[8],fa[3]=t[12],this._state.modelMatrixCol0Buf.setData(fa,i),fa[0]=t[1],fa[1]=t[5],fa[2]=t[9],fa[3]=t[13],this._state.modelMatrixCol1Buf.setData(fa,i),fa[0]=t[2],fa[1]=t[6],fa[2]=t[10],fa[3]=t[14],this._state.modelMatrixCol2Buf.setData(fa,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Ns.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Ns.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ns.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ns.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const ma=c.vec3(),_a=c.vec3(),va=c.mat4();class ba{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ma;if(g){const t=c.transformPoint3(u,A,_a);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,va)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ya{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ba(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Ba={};class xa{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class wa{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Pa{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const Ca={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ca,null,4));let e=0;Object.keys(Ca).forEach((t=>{t.startsWith("size")&&(e+=Ca[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ca.totalLines).toFixed(2)}`);let t={};Object.keys(Ca).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ca[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Ma{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);Ca.sizeDataColorsAndFlags+=l.byteLength,Ca.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ca.sizeDataTextureOffsets+=r.byteLength,Ca.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ca.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ba[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new xa,this._dataTextureState=new wa,this._dataTextureGenerator=new Ma,this._state=new $e({origin:c.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ca.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*Ea||t+r>4096*Ea)&&Ca.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Ea&&t+r<=4096*Ea}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;Ca.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,Ca.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||Ra),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,Ca.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,Ca.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,Ca.totalLines32Bits+=t.numLines),Ca.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Da))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,Da))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Da))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Sa))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ia))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const Ua=c.vec3(),Oa=c.vec3(),ka=c.vec3();c.vec3();const Na=c.vec4(),Qa=c.mat4();class Ha{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ua;if(g){const t=c.transformPoint3(u,A,Oa);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(r.viewMatrix,e,Qa),f=ka,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Va=new Float32Array([1,1,1]),ja=c.vec3(),Ga=c.vec3(),za=c.vec3();c.vec3();const Ka=c.mat4();class Wa{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=ja;if(A){const t=Ga;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,Ka),g=za,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Ns.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Va);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xa=new Float32Array([0,0,0,1]),Ja=c.vec3(),Ya=c.vec3();c.vec3();const Za=c.mat4();class qa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ja;if(g){const t=c.transformPoint3(u,A,Ya);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,Za)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Ns.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Xa);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 $a=c.vec3(),el=c.vec3(),tl=c.mat4();class il{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=$a;if(g){const t=c.transformPoint3(u,A,el);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,tl)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 sl=c.vec3(),rl=c.vec3(),ol=c.vec3(),nl=c.mat4();class al{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=sl;if(g){const t=c.transformPoint3(u,A,rl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(o.viewMatrix,e,nl),f=ol,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ll=c.vec3(),Al=c.vec3(),hl=c.vec3();c.vec3();const cl=c.mat4();class ul{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=ll;if(A){const e=Al;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=V(p,t,cl),g=hl,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 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 dl=c.vec3(),pl=c.vec3(),fl=c.vec3(),gl=c.vec3();c.vec3();const ml=c.mat4();class _l{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=dl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=pl;if(v){const e=c.transformPoint3(u,A,fl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=V(f,t,ml),_=gl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(x,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(x,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(x,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 i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vl=c.vec3(),bl=c.vec3(),yl=c.vec3(),Bl=c.vec3();c.vec3();const xl=c.mat4();class wl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=vl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=bl;if(v){const e=yl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=V(f,t,xl),_=Bl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Pl=c.vec3(),Cl=c.vec3(),Ml=c.vec3();c.vec3();const Fl=c.mat4();class El{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Pl;if(A){const t=Cl;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,Fl),g=Ml,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Il=c.vec3(),Dl=c.vec3(),Sl=c.vec3();c.vec3();const Tl=c.mat4();class Rl{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Il;if(g){const t=c.transformPoint3(u,A,Dl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(r.viewMatrix,e,Tl),f=Sl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new 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("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ll=c.vec3(),Ul=c.vec3(),Ol=c.vec3();c.vec3();const kl=c.mat4();class Nl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=Ll;if(g){const t=Ul;c.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=V(d,e,kl),f=Ol,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(xe.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&xe.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&&xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ql=c.vec3(),Hl=c.vec3(),Vl=c.vec3();c.vec3(),c.vec4();const jl=c.mat4();class Gl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ql;if(g){const t=c.transformPoint3(u,A,Hl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(r.viewMatrix,e,jl),f=Vl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Wa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new al(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gl(this._scene)),this._snapRenderer||(this._snapRenderer=new _l(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new wl(this._scene)),this._snapRenderer||(this._snapRenderer=new _l(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ha(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ha(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Wa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Rl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Nl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new qa(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new il(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new al(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Gl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new _l(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new wl(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new El(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Kl={};class Wl{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Xl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Jl={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Jl,null,4));let e=0;Object.keys(Jl).forEach((t=>{t.startsWith("size")&&(e+=Jl[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Jl.totalPolygons).toFixed(2)}`);let t={};Object.keys(Jl).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Jl[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Yl{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Jl.sizeDataColorsAndFlags+=h.byteLength,Jl.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Jl.sizeDataTextureOffsets+=r.byteLength,Jl.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Jl.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Kl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Wl,this._dtxState=new Xl,this._dtxTextureFactory=new Yl,this._state=new $e({origin:c.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Jl.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*ql||t+r>4096*ql)&&Jl.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*ql&&t+r<=4096*ql}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Jl.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Jl.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Jl.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||sA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Jl.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Jl.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Jl.totalPolygons32Bits+=t.numTriangles),Jl.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Jl.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Jl.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Jl.totalEdges32Bits+=t.numEdges),Jl.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,eA)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,eA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,eA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,tA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,$l))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Ns.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Ns.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Ns.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Ns.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Ns.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Ns.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Ns.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Ns.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ns.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ns.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,Ns.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class oA{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class nA{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const aA={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class lA{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==cA[e])return void cA[e].push({onLoad:t,onProgress:i,onError:s});cA[e]=[],cA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=cA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{aA.add(e,t);const i=cA[e];delete cA[e];for(let e=0,s=i.length;e{const i=cA[e];if(void 0===i)throw this.manager.itemError(e),t;delete cA[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class dA{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let pA=0;class fA{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new dA,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new uA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new uA;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=fA.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(fA.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(fA.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(fA.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),pA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),pA++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),pA--}}fA.BasisFormat={ETC1S:0,UASTC_4x4:1},fA.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},fA.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},fA.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete gA[t],i.destroy()}))),i} +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let o=!0,n=o?Float64Array:Float32Array;const a=new n(3),l=new n(16),A=new n(16),h=new n(4),c={setDoublePrecisionEnabled(e){o=e,n=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>c.dotVec4(e,e),lenVec4:e=>Math.sqrt(c.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=>c.dotVec3(e,e),sqLenVec2:e=>c.dotVec2(e,e),lenVec3:e=>Math.sqrt(c.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>c.lenVec3(c.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(c.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>c.lenVec2(c.subVec2(t,i,e))})(),rcpVec3:(e,t)=>c.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/c.lenVec4(e);return c.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/c.lenVec3(e);return c.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/c.lenVec2(e);return c.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=c.dotVec3(e,t)/Math.sqrt(c.sqLenVec3(e)*c.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=c.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=c.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=c.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||c.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:()=>c.m4s(0),setMat4ToOnes:()=>c.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>c.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>c.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>c.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],B=t[3],x=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+B*f,i[1]=v*r+b*l+y*u+B*g,i[2]=v*o+b*A+y*d+B*m,i[3]=v*n+b*h+y*p+B*_,i[4]=x*s+w*a+P*c+C*f,i[5]=x*r+w*l+P*u+C*g,i[6]=x*o+w*A+P*d+C*m,i[7]=x*n+w*h+P*p+C*_,i[8]=M*s+F*a+E*c+I*f,i[9]=M*r+F*l+E*u+I*g,i[10]=M*o+F*A+E*d+I*m,i[11]=M*n+F*h+E*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*g+A*v,i[4]=a*p+l*m+A*b,i[7]=a*f+l*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=c.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,B=s*A-o*a,x=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,F=c*m-d*f,E=u*m-d*g,I=1/(_*E-v*F+b*M+y*C-B*P+x*w);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*x-g*B+m*y)*I,t[3]=(-c*x+u*B-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*x+g*b-m*v)*I,t[7]=(h*x-u*b+d*v)*I,t[8]=(n*F-a*C+A*w)*I,t[9]=(-i*F+s*C-o*w)*I,t[10]=(p*B-f*b+m*_)*I,t[11]=(-h*B+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||c.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||c.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.translationMat4v(e,r))})(),translationMat4s:(e,t)=>c.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>c.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=c.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,u,d,p,f,g;return h=a*l,u=l*A,d=A*a,p=a*r,f=l*r,g=A*r,(i=i||c.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*d-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>c.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=c.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=c.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>c.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=c.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,u=s*l,d=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=d+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=c.vec4()){const s=c.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-h,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i},composeMat4:(e,t,i,s=c.mat4())=>(c.quaternionToRotationMat4(t,s),c.scaleMat4v(i,s),c.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=c.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=c.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=c.lenVec3(e);c.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=u,t[9]*=u,t[10]*=u,c.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=c.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],u=t[1],d=t[2];if(r===h&&o===u&&n===d)return c.identityMat4();let p,f,g,m,_,v,b,y,B,x;return p=r-h,f=o-u,g=n-d,x=1/Math.sqrt(p*p+f*f+g*g),p*=x,f*=x,g*=x,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,x=Math.sqrt(m*m+_*_+v*v),x?(x=1/x,m*=x,_*=x,v*=x):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,B=p*_-f*m,x=Math.sqrt(b*b+y*y+B*B),x?(x=1/x,b*=x,y*=x,B*=x):(b=0,y=0,B=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=B,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+B*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>c.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=c.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];c.addVec4(r,s,l),c.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],h=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/h,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/h,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],c.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=c.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],B=e[13],x=e[14],w=e[15];let P;for(let e=0;e{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||c.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||c.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=c.vec4()){const s=e[0]*c.DEGTORAD/2,r=e[1]*c.DEGTORAD/2,o=e[2]*c.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"YXZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"ZXY"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"ZYX"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"YZX"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l-A*h*u):"XZY"===t&&(i[0]=A*a*l-n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l+A*h*u),i},mat4ToQuaternion(e,t=c.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let u;const d=i+n+h;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>h?(u=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>h?(u=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=c.vec4()){const s=Math.sqrt(c.dotVec3(e,e)*c.dotVec3(t,t));let r=s+c.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):c.cross3Vec3(e,t,i),i[3]=r,c.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=c.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||c.vec3(),c.quaternionToRotationMat4(t,e),c.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=c.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-h*-l,i[2]=d*A+p*-l+h*-a-u*-n,i},quaternionToMat4(e,t){t=c.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,u=l*o,d=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+u,t[2]=f-h,t[4]=p-u,t[5]=1-(d+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(d+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=c.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>c.normalizeQuaternion(c.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=c.vec4()){const i=(e=c.normalizeQuaternion(e,h))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],B=e[14],x=e[15];for(s=0;s{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],c.subVec3(t,e,i),Math.abs(c.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=c.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>u?h:u,Math.abs(c.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||c.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||c.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=c.AABB3())=>(e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MAX_DOUBLE,e[3]=c.MIN_DOUBLE,e[4]=c.MIN_DOUBLE,e[5]=c.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=c.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new n(3);return(t,i,s)=>{i=i||c.AABB3();let r,o,n,a=c.MAX_DOUBLE,l=c.MAX_DOUBLE,A=c.MAX_DOUBLE,h=c.MIN_DOUBLE,u=c.MIN_DOUBLE,d=c.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||c.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;ru&&(u=h);return s[3]=u,s}})(),getSphere3Center:(e,t=c.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=c.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MIN_DOUBLE,e[3]=c.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=c.AABB2()){let i,s,r,o,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=c.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(h*h+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,h)=>{h=h||c.vec3();const u=c.subVec3(l,a,e),d=c.subVec3(A,a,t),p=c.cross3Vec3(n,d,i),f=c.dotVec3(u,p);if(f<1e-6)return null;const g=c.subVec3(o,a,s),m=c.dotVec3(g,p);if(m<0||m>f)return null;const _=c.cross3Vec3(g,u,r),v=c.dotVec3(n,_);if(v<0||m+v>f)return null;const b=c.dotVec3(d,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||c.vec3(),o=c.normalizeVec3(o,e);const h=c.subVec3(a,n,t),u=c.subVec3(l,n,i),d=c.cross3Vec3(h,u,s);c.normalizeVec3(d,d);const p=-c.dotVec3(n,d),f=-(c.dotVec3(r,d)+p)/c.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=c.subVec3(n,r,e),A=c.subVec3(o,r,t),h=c.subVec3(s,r,i),u=c.dotVec3(l,l),d=c.dotVec3(l,A),p=c.dotVec3(l,h),f=c.dotVec3(A,A),g=c.dotVec3(A,h),m=u*f-d*d;if(0===m)return null;const _=1/m,v=(f*p-d*g)*_,b=(u*g-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=c.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,h;const u=new Array(n.length/3);let d,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const h=new Float32Array(n.length);for(let u=0;u>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,u;const d=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,c.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],c.transformVec3(i,e,t),c.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(16),i=new n(4),s=new n(4),r=new n(4),o=new n(4);return(n,a,l,A,h,u)=>{const d=c.mulMat4(l,a,e),p=c.inverseMat4(d,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,c.transformVec4(p,i,s),c.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,c.transformVec4(p,r,o),c.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],c.subVec3(o,s,u),c.normalizeVec3(u)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l)=>{c.canvasPosToWorldRay(i,s,r,n,e,t),c.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=c.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],c.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;Aa[3]&&(a[3]=r[t]),r[t+1]a[4]&&(a[4]=r[t+1]),r[t+2]a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};c.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),c.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:m,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s0&&w>0){var t=1e3/w;C+=t,x.push(t),x.length>=30&&(C-=x.shift()),p.frame.fps=Math.round(C/x.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{F()}),100);const E=function(){let e=Date.now();if(w=e-P,P>0&&w>0){var t=1e3/w;C+=t,x.push(t),x.length>=30&&(C-=x.shift()),p.frame.fps=Math.round(C/x.length)}I(e),function(e){for(var t in B.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];B.sceneId=t,B.startTime=i.startTime,B.deltaTime=null!=B.prevTime?B.time-B.prevTime:0,i.fire("tick",B,!0)}B.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(F):requestAnimationFrame(E)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}E();class D{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 D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class U{constructor(){this.planes=[new L,new L,new L,new L,new L,new L]}}function O(e,t,i){const s=c.mulMat4(i,t,R),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],u=s[7],d=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,g-d,b-m),e.planes[1].set(a+r,u+l,g+d,b+m),e.planes[2].set(a-o,u-A,g-p,b-_),e.planes[3].set(a+o,u+A,g+p,b+_),e.planes[4].set(a-n,u-h,g-f,b-v),e.planes[5].set(a+n,u+h,g+f,b+v)}function k(e,t){let i=U.INSIDE;const s=S,r=T;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return U.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=U.INTERSECT)}return i}U.INSIDE=0,U.INTERSECT=1,U.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=c.vec2(),this._canvasMarqueeCorner2=c.vec2(),this._canvasMarquee=c.AABB2(),this._marqueeFrustum=new U,this._marqueeFrustumProjMat=c.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=U.INTERSECT)=>{if(s===U.INTERSECT&&(s=k(this._marqueeFrustum,i.aabb)),s!==U.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);c.frustumMat4(l,A,h*a,u*a,d,1e4,this._marqueeFrustumProjMat),O(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class Q{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const H=c.vec3(),V=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(s,t,i),c.setMat4Translation(s,i,o),o.slice()}}();function j(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function G(e,t,i,s=1e3){const r=c.getPositionsCenter(e,H),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{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&&(c.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){re.set(this._viewPos),re[3]=1,c.transformPoint4(this.scene.camera.projMatrix,re,oe);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+oe[0]/oe[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-oe[1]/oe[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 se?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),j(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class ae{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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,i=this._wire.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)";var s=this._wireClickable.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)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class le{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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 i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class Ae{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 i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-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 he=c.vec3(),ce=c.vec3();class ue extends D{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 i=this.plugin.viewer.scene;this._originMarker=new ne(i,t.origin),this._cornerMarker=new ne(i,t.corner),this._targetMarker=new ne(i,t.target),this._originWorld=c.vec3(),this._cornerWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ae(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ae(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new Ae(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),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=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const d=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>d||f>d||g>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);c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,u=t.length;he.offsetTop+(e.offsetParent&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&u(e.offsetParent));this._onMouseHoverSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this.markerDiv.style.left=u(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class fe extends ne{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||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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||"

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[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 i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}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 i=e[t];this.setField(t,i)}}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 ge=c.vec3(),me=c.vec3(),_e=c.vec3();class ve extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const be=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class ye extends D{constructor(e,t={}){super(e,t),this._backgroundColor=c.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new 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-"+c.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?xe.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?xe.FS_MAX_FLOAT_PRECISION="mediump":xe.FS_MAX_FLOAT_PRECISION="lowp":xe.FS_MAX_FLOAT_PRECISION="mediump",xe.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),xe.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),xe.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),xe.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),xe.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),xe.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),xe.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),xe.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),xe.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),xe.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){xe.SUPPORTED_EXTENSIONS[e]=!0})))}class Pe{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Ce{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function De(e){console.error(e.join("\n"))}class Se{constructor(e,t){this.id=Ee.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 Ce(e,e.VERTEX_SHADER,Ie(this.source.vertex)),this._fragmentShader=new Ce(e,e.FRAGMENT_SHADER,Ie(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void De(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void De(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void De(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void De(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void De(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.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 Re{constructor(e,t){this.scene=e,this.aabb=c.AABB3(),this.origin=c.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-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new Re(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new Re(this._scene,e.origin),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Se(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;ke[0]=o,ke[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,ke),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Se(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Te(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Te(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Te(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Qe=new Float32Array(Ke(17,[0,1])),He=new Float32Array(Ke(17,[1,0])),Ve=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(ze(s,t));return i}(17,4)),je=new Float32Array(2);class Ge{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]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Te(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Te(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Te(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),je[0]=n,je[1]=a,s.uniform2fv(this._uViewport,je),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,He):s.uniform2fv(this._uSampleOffsets,Qe),s.uniform1fv(this._uSampleWeights,Ve);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function ze(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Ke(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class We{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class Xe{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new We(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Je(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const Ye=function(t,i){i=i||{};const s=new Be(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},u=!0,d=!0,f=!0,g=!0,m=!0,_=!0,v=!0,b=!0;const y=new Xe(t);let B=!1;const x=new Ne(t),w=new Ge(t);function P(){u&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),u=!1,d=!0),d&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,f=!0),f&&function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||j>0||k>0||N>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||N>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),N>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||z>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),z>0)for(S=0;S0)for(S=0;S0||W>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||J>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),J>0)for(S=0;S0)for(S=0;S0||Z>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Z>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=d.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let D=null,S=null,T=null,R=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),R=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;S=c.normalizeVec3([t[0]/c.MAX_INT,t[1]/c.MAX_INT,t[2]/c.MAX_INT]),D=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===B&&null==D)return null;let L=null;null!==D&&(L=t.camera.projectWorldPos(D));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===R,h.snappedToVertex="vertex"===R,h.worldPos=D,h.worldNormal=S,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=L||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Oe(t,y),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const qe=new e({});class $e{constructor(e){this.id=qe.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){qe.removeItem(this.id)}}class et extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new $e({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class tt extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),c.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class it extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),c.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class st extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.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(){c.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&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class rt extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new $e({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.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&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ot=c.vec3(),nt=c.vec3(),at=c.vec3(),lt=c.vec3(),At=c.vec3(),ht=c.vec3(),ct=c.vec4(),ut=c.vec4(),dt=c.vec4(),pt=c.mat4(),ft=c.mat4(),gt=c.vec3(),mt=c.vec3(),_t=c.vec3(),vt=c.vec3();class bt extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new $e({deviceMatrix:c.mat4(),hasDeviceMatrix:!1,matrix:c.mat4(),normalMatrix:c.mat4(),inverseMatrix:c.mat4()}),this._perspective=new tt(this),this._ortho=new it(this),this._frustum=new st(this),this._customProjection=new rt(this),this._project=this._perspective,this._eye=c.vec3([0,0,10]),this._look=c.vec3([0,0,0]),this._up=c.vec3([0,1,0]),this._worldUp=c.vec3([0,1,0]),this._worldRight=c.vec3([1,0,0]),this._worldForward=c.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?(c.subVec3(this._eye,this._look,gt),c.normalizeVec3(gt,mt),c.mulVec3Scalar(mt,1e3,_t),c.addVec3(this._look,_t,vt),t=vt):t=this._eye,e.hasDeviceMatrix?(c.lookAtMat4v(t,this._look,this._up,ft),c.mulMat4(e.deviceMatrix,ft,e.matrix)):c.lookAtMat4v(t,this._look,this._up,e.matrix),c.inverseMat4(this._state.matrix,this._state.inverseMatrix),c.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=c.subVec3(this._eye,this._look,ot);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=c.transformPoint3(pt,t,nt),this.eye=c.addVec3(this._look,t,at),this.up=c.transformPoint3(pt,this._up,lt)}orbitPitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._eye,this._look,ot);const i=c.cross3Vec3(c.normalizeVec3(t,nt),c.normalizeVec3(this._up,at));c.rotationMat4v(.0174532925*e,i,pt),t=c.transformPoint3(pt,t,lt),this.up=c.transformPoint3(pt,this._up,At),this.eye=c.addVec3(t,this._look,ht)}yaw(e){let t=c.subVec3(this._look,this._eye,ot);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=c.transformPoint3(pt,t,nt),this.look=c.addVec3(t,this._eye,at),this._gimbalLock&&(this.up=c.transformPoint3(pt,this._up,lt))}pitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._look,this._eye,ot);const i=c.cross3Vec3(c.normalizeVec3(t,nt),c.normalizeVec3(this._up,at));c.rotationMat4v(.0174532925*e,i,pt),this.up=c.transformPoint3(pt,this._up,ht),t=c.transformPoint3(pt,t,lt),this.look=c.addVec3(t,this._eye,At)}pan(e){const t=c.subVec3(this._eye,this._look,ot),i=[0,0,0];let s;if(0!==e[0]){const r=c.cross3Vec3(c.normalizeVec3(t,[]),c.normalizeVec3(this._up,nt));s=c.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=c.mulVec3Scalar(c.normalizeVec3(this._up,at),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=c.mulVec3Scalar(c.normalizeVec3(t,lt),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=c.addVec3(this._eye,i,At),this.look=c.addVec3(this._look,i,ht)}zoom(e){const t=c.subVec3(this._eye,this._look,ot),i=Math.abs(c.lenVec3(t,nt)),s=Math.abs(i+e);if(s<.5)return;const r=c.normalizeVec3(t,at);this.eye=c.addVec3(this._look,c.mulVec3Scalar(r,s),lt)}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=c.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 c.lenVec3(c.subVec3(this._look,this._eye,ot))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=ct,i=ut,s=dt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,c.mulMat4v4(this.viewMatrix,t,i),c.mulMat4v4(this.projMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class yt extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Bt extends yt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new $e({type:"dir",dir:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=c.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];c.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=c.identityMat4()),c.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new We(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class xt extends yt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:c.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class wt extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var Pt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const Ct=function(){const e=c.mat4(),t=c.mat4();return function(i,s){s=s||c.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return c.identityMat4(e),c.translationMat4v(i,e),c.identityMat4(t),c.scalingMat4v([a/h,l/h,A/h],t),c.mulMat4(e,t,s),s}}();var Mt=function(){const e=c.mat4(),t=c.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function It(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Dt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const St={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Et(e,a,"floor","ceil"),s=It(i),o=Dt(e,a,s),o>n&&(r=i,n=o),i=Et(e,a,"ceil","ceil"),s=It(i),o=Dt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Tt=p.memory,Rt=c.AABB3();class Lt extends wt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new $e({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=St.getPositionsBounds(t.positions),s=St.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=St.getUVBounds(t.uv),s=St.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=St.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Tt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Tt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Te(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Tt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new Te(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Tt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Te(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Tt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Te(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Tt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=Pt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Tt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=c.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Te(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Tt.positions+=this._pickTrianglePositionsBuf.numItems,Tt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),St.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=St.getPositionsBounds(e),s=St.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),St.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),St.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=c.AABB3()),c.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=c.OBB3()),c.positions3ToAABB3(this._state.positions,Rt,this._state.positionsDecodeMatrix),c.AABB3ToOBB3(Rt,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Tt.meshes--}}function Ut(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Ot extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const kt={opaque:0,mask:1,blend:2},Nt=["opaque","mask","blend"];class Qt extends Ot{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new $e({type:"PhongMaterial",ambient:c.vec3([1,1,1]),diffuse:c.vec3([1,1,1]),specular:c.vec3([1,1,1]),emissive:c.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=kt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Nt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Ht={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Vt extends Ot{get type(){return"EmphasisMaterial"}get presets(){return Ht}constructor(e,t={}){super(e,t),this._state=new $e({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Ht[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ht).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const jt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Gt extends Ot{get type(){return"EdgeMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new $e({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=jt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(jt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const zt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Kt extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=c.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return zt}set units(e){e||(e="meters");zt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=c.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=c.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class Wt extends D{constructor(e,t={}){super(e,t),this._supported=xe.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const Xt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Jt extends Ot{get type(){return"PointsMaterial"}get presets(){return Xt}constructor(e,t={}){super(e,t),this._state=new $e({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=Xt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Xt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Zt extends Ot{get type(){return"LinesMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new $e({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function qt(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Ye(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=c.vec4([0,0,0,0]),t=c.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+_.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=c.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],_.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=qt(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=qt(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=c.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ei=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=si(e),u=s.getNumAllocatedSectionPlanes()>0,d=ii(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=si(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=ii(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+ti[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+ti[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ti[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ti[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ti[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ti[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class li{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ai=new e({}),hi=c.vec3(),ci=function(e,t){this.id=Ai.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new li(t),this._allocate(t)},ui={};ci.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ui[t];return i||(i=new ci(t,e),ui[t]=i,p.memory.programs++),i._useCount++,i},ci.prototype.put=function(){0==--this._useCount&&(Ai.removeItem(this.id),this._program&&this._program.destroy(),delete ui[this._hash],p.memory.programs--)},ci.prototype.webglContextRestored=function(){this._program=null},ci.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const pi=new e({}),fi=c.vec3(),gi=function(e,t){this.id=pi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new di(t),this._allocate(t)},mi={};gi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=mi[t];return i||(i=new gi(t,e),mi[t]=i,p.memory.programs++),i._useCount++,i},gi.prototype.put=function(){0==--this._useCount&&(pi.removeItem(this.id),this._program&&this._program.destroy(),delete mi[this._hash],p.memory.programs--)},gi.prototype.webglContextRestored=function(){this._program=null},gi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const vi=c.vec3(),bi=function(e,t){this._hash=e,this._shaderSource=new _i(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},yi={};bi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=yi[t];if(!i){if(i=new bi(t,e),i.errors)return console.log(i.errors.join("\n")),null;yi[t]=i,p.memory.programs++}return i._useCount++,i},bi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete yi[this._hash],p.memory.programs--)},bi.prototype.webglContextRestored=function(){this._program=null},bi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},bi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Se(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const xi=c.vec3(),wi=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Bi(t),this._allocate(t)},Pi={};wi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Pi[t];if(!i){if(i=new wi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Pi[t]=i,p.memory.programs++}return i._useCount++,i},wi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Pi[this._hash],p.memory.programs--)},wi.prototype.webglContextRestored=function(){this._program=null},wi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Mi=c.vec3(),Fi=function(e,t){this._hash=e,this._shaderSource=new Ci(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ei={};Fi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ei[t];if(!i){if(i=new Fi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ei[t]=i,p.memory.programs++}return i._useCount++,i},Fi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ei[this._hash],p.memory.programs--)},Fi.prototype.webglContextRestored=function(){this._program=null},Fi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Di=function(e,t){this._hash=e,this._shaderSource=new Ii(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Si={};Di.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Si[i];if(!s){if(s=new Di(i,e),s.errors)return console.log(s.errors.join("\n")),null;Si[i]=s,p.memory.programs++}return s._useCount++,s},Di.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Si[this._hash],p.memory.programs--)},Di.prototype.webglContextRestored=function(){this._program=null},Di.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Di.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Se(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const zi=function(){const e=c.vec3(),t=c.vec3(),i=c.vec3(),s=c.vec3(),r=c.vec3(),o=c.vec3(),n=c.vec4(),a=c.vec3(),l=c.vec3(),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3(),m=c.vec4(),_=c.vec4(),v=c.vec4(),b=c.vec3(),y=c.vec3(),B=c.vec3(),x=c.vec3(),w=c.vec3(),P=c.vec3(),C=c.vec3(),M=c.vec3(),F=c.vec3(),E=c.vec3(),I=c.vec3();return function(D,S,T,R){var L=R.primIndex;if(null!=L&&L>-1){const N=D.geometry._state,Q=D.scene,H=Q.camera,j=Q.canvas;if("triangles"===N.primitiveName){R.primitive="triangle";const Q=L,G=N.indices,z=N.positions;let K,W,X;if(G){var U=G[Q+0],O=G[Q+1],k=G[Q+2];o[0]=U,o[1]=O,o[2]=k,R.indices=o,K=3*U,W=3*O,X=3*k}else K=3*Q,W=K+3,X=W+3;if(i[0]=z[K+0],i[1]=z[K+1],i[2]=z[K+2],s[0]=z[W+0],s[1]=z[W+1],s[2]=z[W+2],r[0]=z[X+0],r[1]=z[X+1],r[2]=z[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(St.decompressPosition(i,e,i),St.decompressPosition(s,e,s),St.decompressPosition(r,e,r))}R.canvasPos?c.canvasPosToLocalRay(j.canvas,D.origin?V(S,D.origin):S,T,D.worldMatrix,R.canvasPos,e,t):R.origin&&R.direction&&c.worldRayToLocalRay(D.worldMatrix,R.origin,R.direction,e,t),c.normalizeVec3(t),c.rayPlaneIntersect(e,t,i,s,r,n),R.localPos=n,R.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,c.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],R.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),R.worldPos=a,c.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],R.viewPos=l,c.cartesianToBarycentric(n,i,s,r,A),R.bary=A;const J=N.normals;if(J){if(N.compressGeometry){const e=3*U,t=3*O,i=3*k;St.decompressNormal(J.subarray(e,e+2),h),St.decompressNormal(J.subarray(t,t+2),u),St.decompressNormal(J.subarray(i,i+2),d)}else h[0]=J[K],h[1]=J[K+1],h[2]=J[K+2],u[0]=J[W],u[1]=J[W+1],u[2]=J[W+2],d[0]=J[X],d[1]=J[X+1],d[2]=J[X+2];const e=c.addVec3(c.addVec3(c.mulVec3Scalar(h,A[0],b),c.mulVec3Scalar(u,A[1],y),B),c.mulVec3Scalar(d,A[2],x),w);R.worldNormal=c.normalizeVec3(c.transformVec3(D.worldNormalMatrix,e,P))}const Y=N.uv;if(Y){if(p[0]=Y[2*U],p[1]=Y[2*U+1],f[0]=Y[2*O],f[1]=Y[2*O+1],g[0]=Y[2*k],g[1]=Y[2*k+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(St.decompressUV(p,e,p),St.decompressUV(f,e,f),St.decompressUV(g,e,g))}R.uv=c.addVec3(c.addVec3(c.mulVec2Scalar(p,A[0],C),c.mulVec2Scalar(f,A[1],M),F),c.mulVec2Scalar(g,A[2],E),I)}}}}}();function Ki(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],v=[],b=[];let y,B,x,w,P,C,M,F,E,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=c-y*u,B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),m.push(P*x),m.push(S),m.push(P*w),v.push(B*p),v.push(1*y/o),g.push(P*x+l),g.push(C+A),g.push(P*w+h);for(y=0;y0){for(E=g.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(t*x),m.push(1),m.push(t*w),v.push(I),v.push(D),g.push(t*x+l),g.push(c+A),g.push(t*w+h);for(B=0;B0){for(E=g.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(i*x),m.push(-1),m.push(i*w),v.push(I),v.push(D),g.push(i*x+l),g.push(0-c+A),g.push(i*w+h);for(B=0;B":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Ji(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,v=(l||"").split("\n"),b=0,y=0,B=.04,x=0;x0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=ps(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ps(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ps(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,_s(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,_s(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ps(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ps(i,this.magFilter)));const a=ps(i,this.format,this.encoding),l=ps(i,this.type),A=ms(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Bs extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new $e({texture:new gs({gl:this.scene.canvas.gl}),matrix:c.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=c.vec2([0,0]),this._scale=c.vec2([1,1]),this._rotate=c.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),p.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new gs({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=c.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=c.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?c.mulMat4(t,i):i),0!==this._rotate&&(i=c.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?c.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=vs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=vs(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const xs=p.memory,ws=c.AABB3();class Ps extends wt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new $e({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=c.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=St.getPositionsBounds(t.positions),o=St.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new Te(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),xs.positions+=i.positionsBuf.numItems,c.positions3ToAABB3(t.positions,this._aabb),c.positions3ToAABB3(r,ws,i.positionsDecodeMatrix),c.AABB3ToOBB3(ws,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new Te(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),xs.colors+=i.colorsBuf.numItems}if(t.uv){const e=St.getUVBounds(t.uv),r=St.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new Te(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),xs.uvs+=i.uvBuf.numItems}if(t.normals){const e=St.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new Te(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),xs.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),xs.indices+=i.indicesBuf.numItems;const o=Pt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),xs.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),xs.meshes--}}var Cs={};function Ms(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Fs(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Es(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,B,x,w,P,C,M,F=0,E=0;for(y=0;y65535?Uint32Array:Uint16Array)(c*u*6);for(y=0;y360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],u=[],d=[],p=[];let f,g,m,v,b,y,B,x,w,P,C,M;for(x=0;x<=r;x++)for(B=0;B<=s;B++)f=B/s*o,g=.785398+x/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),v=(t+i*Math.cos(g))*Math.sin(f),b=i*Math.sin(g),h.push(m+a),h.push(v+l),h.push(b+A),d.push(1-B/s),d.push(x/r),y=c.normalizeVec3(c.subVec3([m,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(x=1;x<=r;x++)for(B=1;B<=s;B++)w=(s+1)*x+B-1,P=(s+1)*(x-1)+B-1,C=(s+1)*(x-1)+B,M=(s+1)*x+B,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return _.apply(e,{positions:h,normals:u,uv:d,indices:p})}function Ds(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e>8},Cs.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Cs.parse={},Cs.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Ss extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=c.vec3(t.pos||[0,0,0]),this._up=c.vec3(t.up||[0,1,0]),this._normal=c.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=c.vec3(),this._rtcPos=c.vec3(),this._imageSize=c.vec2(),this._texture=new Bs(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new ns(this,{matrix:c.inverseMat4(c.lookAtMat4v(this._pos,c.subVec3(this._pos,this._normal,c.mat4()),this._up,c.mat4())),children:[this._bitmapMesh=new Gi(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Lt(this,Es({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Qt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const Ts=c.OBB3(),Rs=c.OBB3(),Ls=c.OBB3();class Us{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=c.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(c.AABB3ToOBB3(this._aabbLocal,Ts),this.transform?(c.transformOBB3(this.transform.worldMatrix,Ts,Rs),c.transformOBB3(this.model.worldMatrix,Rs,Ls),c.OBB3ToAABB3(Ls,this._aabbWorld)):(c.transformOBB3(this.model.worldMatrix,Ts,Rs),c.OBB3ToAABB3(Rs,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const Os=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let ks=0;const Ns={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Qs=new Float32Array([1,1,1,1]),Hs=new Float32Array([0,0,0,1]),Vs=c.vec4(),js=c.vec3(),Gs=c.vec3(),zs=c.mat4();class Ks{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;Vs[0]=i,Vs[1]=s,Vs[2]=t.blendCutoff,Vs[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Vs),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Ns[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ns[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Ns[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?Hs:Qs)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class Ws extends Ks{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Xs extends Ws{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class Js extends Ws{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = vColor;"),o.push("}"),o}}class Zs extends Ws{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class qs extends Zs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class $s extends Zs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class er extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class tr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ir extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class sr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class rr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class or extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class nr extends Ws{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class ar extends Ws{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Ar extends Ws{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gr=c.vec3(),mr=c.vec3(),_r=c.vec3(),vr=c.vec3(),br=c.mat4();class yr extends Ks{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=gr;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=mr;if(l){const e=_r;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,br),m=vr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Br{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ys(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new er(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new tr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new fr(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new yr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Xs(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Xs(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Js(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Js(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ar(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ar(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ar(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ar(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ys(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new rr(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new or(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new qs(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new $s(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new er(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ir(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new lr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new tr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new sr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new nr(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new yr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new fr(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const xr={};let wr=65536,Pr=5e6;class Cr{constructor(){}set doublePrecisionEnabled(e){c.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return c.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),wr=e}get maxDataTextureHeight(){return wr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Pr=e}get maxGeometryBatchSize(){return Pr}}const Mr=new Cr;class Fr{constructor(){this.maxVerts=Mr.maxGeometryBatchSize,this.maxIndices=3*Mr.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Er=c.mat4(),Ir=c.mat4();function Dr(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,u=65525,d=u/l,p=u/A,f=u/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function Rr(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Lr=c.mat4(),Ur=c.mat4(),Or=c.vec4([0,0,0,1]),kr=c.vec3(),Nr=c.vec3(),Qr=c.vec3(),Hr=c.vec3(),Vr=c.vec3(),jr=c.vec3(),Gr=c.vec3();class zr{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=xr[t];return i||(i=new Br(e),xr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete xr[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Fr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new $e({origin:c.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=c.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=c.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Lr;m?c.inverseMat4(c.transposeMat4(m,Ur),e):c.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;uh&&(l=n,h=A),n=Tr(p,"floor","ceil"),a=Rr(n),A=o(p,a),A>h&&(l=n,h=A),n=Tr(p,"ceil","ceil"),a=Rr(n),A=o(p,a),A>h&&(l=n,h=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Dr(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=c.mat4());if(e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new Te(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new Te(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=St.getUVBounds(i.uv),r=St.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=c.mat3(r.decodeMatrix),e.uvBuf=new Te(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Te(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Te(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&c.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Kr extends Ks{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Wr extends Kr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class Xr extends Kr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Yr extends Kr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Zr extends Yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class qr extends Yr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class $r extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class eo extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class to extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class io extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class so extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class ro extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class oo extends Kr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const no={3e3:"linearToLinear",3001:"sRGBToLinear"};class ao extends Kr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+no[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+no[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class Ao extends Kr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const mo=c.vec3(),_o=c.vec3(),vo=c.vec3(),bo=c.vec3(),yo=c.mat4();class Bo extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=mo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=_o;if(l){const e=c.transformPoint3(h,l,vo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,yo),m=bo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class xo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Jr(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new $r(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new eo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new go(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Bo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Wr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Xr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Xr(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ao(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ao(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ao(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ao(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new so(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ro(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Zr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new qr(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new $r(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new to(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new lo(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new eo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new io(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new oo(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new go(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Bo(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const wo={};const Po=new Uint8Array(4),Co=new Float32Array(1),Mo=c.vec4([0,0,0,1]),Fo=new Float32Array(3),Eo=c.vec3(),Io=c.vec3(),Do=c.vec3(),So=c.vec3(),To=c.vec3(),Ro=c.vec3(),Lo=c.vec3(),Uo=new Float32Array(4);class Oo{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=wo[t];return i||(i=new xo(e),wo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete wo[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new $e({numInstances:0,obb:c.OBB3(),origin:c.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Te(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Te(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new Te(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new Te(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=c.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Te(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Te(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Te(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Te(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Te(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Po[0]=t[0],Po[1]=t[1],Po[2]=t[2],Po[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Po,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&Z),o=!!(t&q),n=!!(t&$),a=!!(t&ee),l=!!(t&X),A=!!(t&W);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ns.NOT_RENDERED:i?Ns.COLOR_TRANSPARENT:Ns.COLOR_OPAQUE,c=!s||A?Ns.NOT_RENDERED:n?Ns.SILHOUETTE_SELECTED:o?Ns.SILHOUETTE_HIGHLIGHTED:r?Ns.SILHOUETTE_XRAYED:Ns.NOT_RENDERED;let u=0;u=!s||A?Ns.NOT_RENDERED:n?Ns.EDGES_SELECTED:o?Ns.EDGES_HIGHLIGHTED:r?Ns.EDGES_XRAYED:a?i?Ns.EDGES_COLOR_TRANSPARENT:Ns.EDGES_COLOR_OPAQUE:Ns.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ns.PICK:Ns.NOT_RENDERED)<<12,d|=(t&J?1:0)<<16,Co[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Co,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Fo[0]=t[0],Fo[1]=t[1],Fo[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Fo,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],u=Mo,d=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&c.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(c.transformVec3(a.normalMatrix,r,r),c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ko extends Ks{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class No extends ko{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Qo extends ko{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Ho=c.vec3(),Vo=c.vec3(),jo=c.vec3(),Go=c.vec3(),zo=c.mat4();class Ko extends Ks{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ho;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Vo;if(l){const e=jo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,zo),m=Go,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Wo=c.vec3(),Xo=c.vec3(),Jo=c.vec3(),Yo=c.vec3(),Zo=c.mat4();class qo extends Ks{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Wo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Xo;if(l){const e=Jo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,Zo),m=Yo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class $o{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new No(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Qo(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ko(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new qo(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const en={};class tn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class sn{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=en[t];return i||(i=new $o(e),en[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete en[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new tn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new $e({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Dr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Te(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Te(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class nn extends rn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const an=c.vec3(),ln=c.vec3(),An=c.vec3();c.vec3();const hn=c.mat4();class cn extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=an;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ln;if(l){const e=c.transformPoint3(h,l,An);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,hn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const un=c.vec3(),dn=c.vec3(),pn=c.vec3();c.vec3();const fn=c.mat4();class gn extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=un;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=dn;if(l){const e=c.transformPoint3(h,l,pn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,fn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class mn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new cn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new gn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new on(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new nn(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new cn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new gn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const _n={};const vn=new Uint8Array(4),bn=new Float32Array(1),yn=new Float32Array(3),Bn=new Float32Array(4);class xn{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=_n[t];return i||(i=new mn(e),_n[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete _n[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new $e({obb:c.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=c.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Te(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new Te(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new Te(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=c.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Te(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";vn[0]=t[0],vn[1]=t[1],vn[2]=t[2],vn[3]=t[3],this._state.colorsBuf.setData(vn,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&Z),o=!!(t&q),n=!!(t&$),a=!!(t&ee),l=!!(t&X),A=!!(t&W);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ns.NOT_RENDERED:i?Ns.COLOR_TRANSPARENT:Ns.COLOR_OPAQUE,c=!s||A?Ns.NOT_RENDERED:n?Ns.SILHOUETTE_SELECTED:o?Ns.SILHOUETTE_HIGHLIGHTED:r?Ns.SILHOUETTE_XRAYED:Ns.NOT_RENDERED;let u=0;u=!s||A?Ns.NOT_RENDERED:n?Ns.EDGES_SELECTED:o?Ns.EDGES_HIGHLIGHTED:r?Ns.EDGES_XRAYED:a?i?Ns.EDGES_COLOR_TRANSPARENT:Ns.EDGES_COLOR_OPAQUE:Ns.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ns.PICK:Ns.NOT_RENDERED)<<12,d|=(t&J?255:0)<<16,bn[0]=d,this._state.flagsBuf.setData(bn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(yn[0]=t[0],yn[1]=t[1],yn[2]=t[2],this._state.offsetsBuf.setData(yn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Bn[0]=t[0],Bn[1]=t[4],Bn[2]=t[8],Bn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Bn,i),Bn[0]=t[1],Bn[1]=t[5],Bn[2]=t[9],Bn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Bn,i),Bn[0]=t[2],Bn[1]=t[6],Bn[2]=t[10],Bn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Bn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ns.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ns.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class wn extends Ks{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Pn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Cn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class Mn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Fn extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class En extends wn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const In=c.vec3(),Dn=c.vec3(),Sn=c.vec3(),Tn=c.vec3(),Rn=c.mat4();class Ln extends Ks{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=In;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Dn;if(l){const e=Sn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,Rn),m=Tn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Un=c.vec3(),On=c.vec3(),kn=c.vec3(),Nn=c.vec3(),Qn=c.mat4();class Hn extends Ks{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Un;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=On;if(l){const e=kn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,Qn),m=Nn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Vn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Pn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Cn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Mn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Fn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new En(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ln(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Hn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const jn={};class Gn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class zn{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=jn[t];return i||(i=new Vn(e),jn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete jn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Gn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new $e({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Dr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Te(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new Te(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Te(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Te(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Xn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Jn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Yn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Zn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class qn extends Kn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class $n extends Kn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const ea=c.vec3(),ta=c.vec3(),ia=c.vec3();c.vec3();const sa=c.mat4();class ra extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ea;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ta;if(l){const e=c.transformPoint3(h,l,ia);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,sa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const oa=c.vec3(),na=c.vec3(),aa=c.vec3();c.vec3();const la=c.mat4();class Aa extends Ks{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=oa;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=na;if(l){const e=c.transformPoint3(h,l,aa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=V(p,t,la),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ha{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Xn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new qn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Jn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Zn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new $n(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ra(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Aa(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const ca={};const ua=new Uint8Array(4),da=new Float32Array(1),pa=new Float32Array(3),fa=new Float32Array(4);class ga{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=ca[t];return i||(i=new ha(e),ca[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete ca[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new $e({obb:c.OBB3(),numInstances:0,origin:e.origin?c.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new Te(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=c.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new Te(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new Te(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new Te(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";ua[0]=t[0],ua[1]=t[1],ua[2]=t[2],this._state.colorsBuf.setData(ua,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&Z),o=!!(t&q),n=!!(t&$),a=!!(t&ee),l=!!(t&X),A=!!(t&W);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Ns.NOT_RENDERED:i?Ns.COLOR_TRANSPARENT:Ns.COLOR_OPAQUE,c=!s||A?Ns.NOT_RENDERED:n?Ns.SILHOUETTE_SELECTED:o?Ns.SILHOUETTE_HIGHLIGHTED:r?Ns.SILHOUETTE_XRAYED:Ns.NOT_RENDERED;let u=0;u=!s||A?Ns.NOT_RENDERED:n?Ns.EDGES_SELECTED:o?Ns.EDGES_HIGHLIGHTED:r?Ns.EDGES_XRAYED:a?i?Ns.EDGES_COLOR_TRANSPARENT:Ns.EDGES_COLOR_OPAQUE:Ns.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Ns.PICK:Ns.NOT_RENDERED)<<12,d|=(t&J?255:0)<<16,da[0]=d,this._state.flagsBuf.setData(da,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(pa[0]=t[0],pa[1]=t[1],pa[2]=t[2],this._state.offsetsBuf.setData(pa,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;fa[0]=t[0],fa[1]=t[4],fa[2]=t[8],fa[3]=t[12],this._state.modelMatrixCol0Buf.setData(fa,i),fa[0]=t[1],fa[1]=t[5],fa[2]=t[9],fa[3]=t[13],this._state.modelMatrixCol1Buf.setData(fa,i),fa[0]=t[2],fa[1]=t[6],fa[2]=t[10],fa[3]=t[14],this._state.modelMatrixCol2Buf.setData(fa,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Ns.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Ns.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ns.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ns.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const ma=c.vec3(),_a=c.vec3(),va=c.mat4();class ba{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ma;if(g){const t=c.transformPoint3(u,A,_a);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,va)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ya{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ba(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Ba={};class xa{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class wa{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Pa{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const Ca={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ca,null,4));let e=0;Object.keys(Ca).forEach((t=>{t.startsWith("size")&&(e+=Ca[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ca.totalLines).toFixed(2)}`);let t={};Object.keys(Ca).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ca[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Ma{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);Ca.sizeDataColorsAndFlags+=l.byteLength,Ca.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ca.sizeDataTextureOffsets+=r.byteLength,Ca.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ca.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ba[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new xa,this._dataTextureState=new wa,this._dataTextureGenerator=new Ma,this._state=new $e({origin:c.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ca.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*Ea||t+r>4096*Ea)&&Ca.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Ea&&t+r<=4096*Ea}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;Ca.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,Ca.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||Ra),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,Ca.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,Ca.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,Ca.totalLines32Bits+=t.numLines),Ca.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Da))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,Da))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Da))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Sa))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ia))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const Ua=c.vec3(),Oa=c.vec3(),ka=c.vec3();c.vec3();const Na=c.vec4(),Qa=c.mat4();class Ha{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ua;if(g){const t=c.transformPoint3(u,A,Oa);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(r.viewMatrix,e,Qa),f=ka,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Se(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Va=new Float32Array([1,1,1]),ja=c.vec3(),Ga=c.vec3(),za=c.vec3();c.vec3();const Ka=c.mat4();class Wa{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=ja;if(A){const t=Ga;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,Ka),g=za,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Ns.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Va);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xa=new Float32Array([0,0,0,1]),Ja=c.vec3(),Ya=c.vec3();c.vec3();const Za=c.mat4();class qa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ja;if(g){const t=c.transformPoint3(u,A,Ya);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,Za)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Ns.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Ns.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Xa);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 $a=c.vec3(),el=c.vec3(),tl=c.mat4();class il{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=$a;if(g){const t=c.transformPoint3(u,A,el);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,tl)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 sl=c.vec3(),rl=c.vec3(),ol=c.vec3(),nl=c.mat4();class al{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=sl;if(g){const t=c.transformPoint3(u,A,rl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(o.viewMatrix,e,nl),f=ol,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ll=c.vec3(),Al=c.vec3(),hl=c.vec3();c.vec3();const cl=c.mat4();class ul{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=ll;if(A){const e=Al;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=V(p,t,cl),g=hl,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 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 dl=c.vec3(),pl=c.vec3(),fl=c.vec3(),gl=c.vec3();c.vec3();const ml=c.mat4();class _l{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=dl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=pl;if(v){const e=c.transformPoint3(u,A,fl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=V(f,t,ml),_=gl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(x,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(x,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(x,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 i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vl=c.vec3(),bl=c.vec3(),yl=c.vec3(),Bl=c.vec3();c.vec3();const xl=c.mat4();class wl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=vl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=bl;if(v){const e=yl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=V(f,t,xl),_=Bl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Pl=c.vec3(),Cl=c.vec3(),Ml=c.vec3();c.vec3();const Fl=c.mat4();class El{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Pl;if(A){const t=Cl;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=V(p,e,Fl),g=Ml,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Il=c.vec3(),Dl=c.vec3(),Sl=c.vec3();c.vec3();const Tl=c.mat4();class Rl{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Il;if(g){const t=c.transformPoint3(u,A,Dl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(r.viewMatrix,e,Tl),f=Sl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new 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("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ll=c.vec3(),Ul=c.vec3(),Ol=c.vec3();c.vec3();const kl=c.mat4();class Nl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=Ll;if(g){const t=Ul;c.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=V(d,e,kl),f=Ol,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(xe.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&xe.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&&xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&xe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ql=c.vec3(),Hl=c.vec3(),Vl=c.vec3();c.vec3(),c.vec4();const jl=c.mat4();class Gl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Ql;if(g){const t=c.transformPoint3(u,A,Hl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=V(r.viewMatrix,e,jl),f=Vl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Se(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Wa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new al(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gl(this._scene)),this._snapRenderer||(this._snapRenderer=new _l(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new wl(this._scene)),this._snapRenderer||(this._snapRenderer=new _l(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ha(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ha(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Wa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Rl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Nl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new qa(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new il(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new al(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Gl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Gl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new _l(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new wl(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new El(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Kl={};class Wl{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Xl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Jl={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Jl,null,4));let e=0;Object.keys(Jl).forEach((t=>{t.startsWith("size")&&(e+=Jl[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Jl.totalPolygons).toFixed(2)}`);let t={};Object.keys(Jl).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Jl[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Yl{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Jl.sizeDataColorsAndFlags+=h.byteLength,Jl.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Jl.sizeDataTextureOffsets+=r.byteLength,Jl.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Pa(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Jl.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Kl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Wl,this._dtxState=new Xl,this._dtxTextureFactory=new Yl,this._state=new $e({origin:c.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Jl.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*ql||t+r>4096*ql)&&Jl.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*ql&&t+r<=4096*ql}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Jl.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Jl.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Jl.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||sA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Jl.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Jl.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Jl.totalPolygons32Bits+=t.numTriangles),Jl.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Jl.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Jl.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Jl.totalEdges32Bits+=t.numEdges),Jl.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Z&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&$&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&J&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&X&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&J?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,eA)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,eA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,eA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,tA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,$l))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Ns.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Ns.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Ns.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Ns.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Ns.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Ns.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Ns.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Ns.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Ns.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Ns.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Ns.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Ns.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Ns.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,Ns.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class oA{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class nA{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const aA={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class lA{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==cA[e])return void cA[e].push({onLoad:t,onProgress:i,onError:s});cA[e]=[],cA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=cA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{aA.add(e,t);const i=cA[e];delete cA[e];for(let e=0,s=i.length;e{const i=cA[e];if(void 0===i)throw this.manager.itemError(e),t;delete cA[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class dA{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let pA=0;class fA{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new dA,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new uA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new uA;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=fA.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(fA.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(fA.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(fA.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),pA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),pA++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),pA--}}fA.BasisFormat={ETC1S:0,UASTC_4x4:1},fA.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},fA.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},fA.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete gA[t],i.destroy()}))),i} /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT @@ -14,7 +14,7 @@ /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT - **/let BA=null;function xA(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const h=Math.min(r=BA[i],o=BA[i+1],n=BA[i+2]),c=Math.min(a=BA[s],l=BA[s+1],A=BA[s+2]);if(h!==c)return h-c;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let wA=null;function PA(e,t){let i=wA[2*e]-wA[2*t];return 0!==i?i:wA[2*e+1]-wA[2*t+1]}function CA(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e>t;i.sort(xA);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}wA=new Int32Array(e),t.sort(PA);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new nA({id:"defaultColorTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new nA({id:"defaultMetalRoughTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new nA({id:"defaultNormalsTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new nA({id:"defaultEmissiveTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new nA({id:"defaultOcclusionTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new oA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),c.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),c.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||HA),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new nA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new oA({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(this.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new RA({id:e.id,model:this,parentTransform:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?c.addVec3(this._origin,e.origin,c.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||OA,i=e.position||kA,s=e.rotation||NA;c.eulerToQuaternion(s,"XYZ",QA),e.meshMatrix=c.composeMat4(i,QA,t,c.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Sr(e.positionsDecodeBoundary,c.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):VA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=c.vec3(),i=[];G(e.positions,i,t)&&(e.positions=i,e.origin=c.addVec3(e.origin,t,t))}if(e.positions){const t=c.collapseAABB3();e.positionsDecodeMatrix=c.mat4(),c.expandAABB3Points3(t,e.positions),e.positionsCompressed=Dr(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=c.collapseAABB3();c.expandAABB3Points3(t,e.positionsCompressed),St.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=c.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=c.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Oo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Oo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new xn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new ga({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=c.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=c.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=K),this._pickable&&!1!==e.pickable&&(t|=X),this._culled&&!1!==e.culled&&(t|=W),this._clippable&&!1!==e.clippable&&(t|=J),this._collidable&&!1!==e.collidable&&(t|=Y),this._edges&&!1!==e.edges&&(t|=ee),this._xrayed&&!1!==e.xrayed&&(t|=Z),this._highlighted&&!1!==e.highlighted&&(t|=q),this._selected&&!1!==e.selected&&(t|=$),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class zA extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class ih extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ne(i,t.origin),this._targetMarker=new ne(i,t.target),this._originWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=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:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ae(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ae(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ae(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ae(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new Ae(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new Ae(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new Ae(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new Ae(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],u=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var d=0,p=s.length;d{const t=e.snappedCanvasPos||e.canvasPos;if(r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState){const i=s.getBoundingClientRect(),r=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,n=i.left+r,a=i.top+o;this._markerDiv.style.left=n+t[0]-5+"px",this._markerDiv.style.top=a+t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity}else this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px";s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class oh{constructor(){}getMetaModel(e,t,i){_.loadJSON(e,(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){_.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){_.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class nh{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=ah(e,i);return s?t?lh(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=ah(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=lh(r,[t]),i&&(r=lh(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function ah(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=c.subVec3(o,r,[]);return c.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=c.lenVec3(c.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class hh extends Ah{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=c.vec3();return A[0]=c.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=c.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=c.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const ch=c.vec3();const uh=c.vec3(),dh=c.vec3(),ph=c.vec3(),fh=c.vec3(),gh=c.vec3();class mh extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=c.vec3(),this._eye1=c.vec3(),this._up1=c.vec3(),this._look2=c.vec3(),this._eye2=c.vec3(),this._up2=c.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const h=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?mh._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(c.subVec3(s.eye,s.look,gh),s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,ph),s.look=c.subVec3(ph,gh,dh)):this._flyingLook&&(s.look=c.lerpVec3(i,0,1,this._look1,this._look2,dh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,fh)):this._flyingEyeLookUp&&(s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,ph),s.look=c.lerpVec3(i,0,1,this._look1,this._look2,dh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,fh)),this._projection2){const t="ortho"===this._projection2?mh._easeOutExpo(e,0,1,1):mh._easeInCubic(e,0,1,1);s.customProjection.matrix=c.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class _h extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new mh(this),this._t=0,this.state=_h.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case _h.SCRUBBING:return;case _h.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=_h.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case _h.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=_h.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=_h.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=_h.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=_h.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=_h.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=_h.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=_h.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}_h.STOPPED=0,_h.SCRUBBING=1,_h.PLAYING=2,_h.PLAYING_TO=3;const vh=c.vec3(),bh=c.vec3();c.vec3();const yh=c.vec3([0,-1,0]),Bh=c.vec4([0,0,0,1]);function xh(e){if(!wh(e.width)||!wh(e.height)){const t=document.createElement("canvas");t.width=Ph(e.width),t.height=Ph(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function wh(e){return 0==(e&e-1)}function Ph(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Ch extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new $e({texture:new gs({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),p.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const Fh=c.vec3();const Eh=c.vec3();class Ih{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,h=!t||t.colorize,c=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),h){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}c&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,h=!t||t.opacity;var c=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[c]),s&&(t.edges=this.objectsEdges[c]),r&&(t.xrayed=this.objectsXrayed[c]),o&&(t.highlighted=this.objectsHighlighted[c]),n&&(t.selected=this.objectsSelected[c]),a&&(t.clippable=this.objectsClippable[c]),l&&(t.pickable=this.objectsPickable[c]),A&&(this.objectsHasColorize[c]?(Eh[0]=this.objectsColorize[3*c+0],Eh[1]=this.objectsColorize[3*c+1],Eh[2]=this.objectsColorize[3*c+2],t.colorize=Eh):t.colorize=null),h&&(t.opacity=this.objectsOpacity[c]),c++}}}class Dh extends D{constructor(e,t={}){super(e,t),this._skyboxMesh=new Gi(this,{geometry:new Lt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Qt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Bs(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}const Sh=c.vec4(),Th=c.vec4(),Rh=c.vec3(),Lh=c.vec3(),Uh=c.vec3(),Oh=c.vec4(),kh=c.vec4(),Nh=c.vec4();class Qh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=c.subVec3(e,r.eye,Rh);s=c.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=c.vec3();c.decomposeMat4(c.inverseMat4(this._scene.viewer.camera.viewMatrix,c.mat4()),t,c.vec4(),c.vec3());const i=c.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),j(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Ps(this._scene,Wi({radius:s})),this._pivotSphere=new Gi(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){c.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,c.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(j(this.getPivotPos(),this._rtcCenter,this._rtcPos),c.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Qt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=c.lookAtMat4v(e.eye,e.look,e.worldUp);c.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=c.distVec3(e.eye,i),t=c.inverseMat4(t);const s=c.transformVec3(t,this._cameraOffset),r=c.vec3();if(c.subVec3(e.eye,i,r),c.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=c.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=c.normalizeVec3(c.subVec3(e.look,e.eye,Hh)),i=c.cross3Vec3(t,e.worldUp,Vh);return c.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(c.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=c.dotVec4(n,r)/c.dotVec4(n,o),l=Gh;t.project.unproject(e,a,zh,Kh,l);const A=c.normalizeVec3(c.subVec3(l,t.eye,Hh)),h=c.addVec3(t.eye,c.mulVec3Scalar(A,i,Vh),jh);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=c.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=c.lenVec3(c.subVec3(i.look,i.eye,c.vec3())),a=this.getPivotPos();c.addVec3(o,a);let l=c.lookAtMat4v(o,a,i.worldUp);l=c.inverseMat4(l);const A=c.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],c.subVec3(i.eye,c.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Xh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=c.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Pe;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Jh=c.vec2();class Yh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,u=0,d=0,p=!1;const f=c.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],u=t[3],d=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l){const t=d-A,i=g-h,s=e.camera;if("perspective"===s.projection){const o=Math.abs(p?c.lenVec3(c.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/u,r.panDeltaY+=1.5*i*o/u}else r.panDeltaX+=.5*s.ortho.scale*(t/u),r.panDeltaY+=.5*s.ortho.scale*(i/u)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=(d-A)/o*i.dragRotationRate/2,r.rotateDeltaX+=(g-h)/u*(i.dragRotationRate/4)):(r.rotateDeltaY-=(d-A)/o*(1.5*i.dragRotationRate),r.rotateDeltaX+=(g-h)/u*(1.5*i.dragRotationRate)));A=d,h=g}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Jh);const i=Jh[0],s=Jh[1];Math.abs(i-u)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Jh,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||u))return;const d=e.aabb,p=c.getAABB3Diag(d);c.getAABB3Center(d,Zh);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*c.DEGTORAD)),g=1.1*p;ic.orthoScale=g,n?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldRight,f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):a?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldForward,f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):l?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldRight,-f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):A?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldForward,-f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):h?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldUp,f,qh),tc)),ic.look.set(Zh),ic.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,1,$h),ec))):u&&(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldUp,-f,qh),tc)),ic.look.set(Zh),ic.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,-1,$h)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Zh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(ic,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(ic),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class rc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),d=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||d)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=d,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",d),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=c.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=c.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class oc{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const nc=c.vec3();class ac{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer&&--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(c.lenVec3(c.subVec3(u,e.camera.eye,nc)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Ac(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Ac(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Ac(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s-window.scrollX,i[1]=e.clientY-r-window.scrollY}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const hc=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class cc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=c.vec2(),l=c.vec2(),A=c.vec2(),h=c.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(hc(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length{n.getPivoting()&&n.endPivot()}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],g=t.touches;if(t.touches.length===p){if(1===p){hc(g[0],l),c.subVec2(l,u[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];hc(t,l),hc(n,A);const a=c.geometricMeanVec2(u[0],u[1]),h=c.geometricMeanVec2(l,A),p=c.vec2();c.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=c.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(c.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(c.lenVec3(c.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=m*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/d)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,uc(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(u>-1&&h-u<325?(uc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):c.distVec2(l[0],A)<4&&(uc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:c.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:c.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Xh(this,this._configs),pivotController:new Wh(i,this._configs),panController:new Qh(i),cameraFlight:new mh(this,{duration:.5})},this._handlers=[new lc(this.scene,this._controllers,this._configs,this._states,this._updates),new cc(this.scene,this._controllers,this._configs,this._states,this._updates),new Yh(this.scene,this._controllers,this._configs,this._states,this._updates),new sc(this.scene,this._controllers,this._configs,this._states,this._updates),new rc(this.scene,this._controllers,this._configs,this._states,this._updates),new dc(this.scene,this._controllers,this._configs,this._states,this._updates),new oc(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new ac(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?bc(t):null,n=i&&i.length>0?bc(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r>t;i.sort(xA);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}wA=new Int32Array(e),t.sort(PA);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new nA({id:"defaultColorTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new nA({id:"defaultMetalRoughTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new nA({id:"defaultNormalsTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new nA({id:"defaultEmissiveTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new nA({id:"defaultOcclusionTexture",texture:new gs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new oA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),c.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),c.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||HA),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new nA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new oA({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(this.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new RA({id:e.id,model:this,parentTransform:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?c.addVec3(this._origin,e.origin,c.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||OA,i=e.position||kA,s=e.rotation||NA;c.eulerToQuaternion(s,"XYZ",QA),e.meshMatrix=c.composeMat4(i,QA,t,c.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Sr(e.positionsDecodeBoundary,c.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):VA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=c.vec3(),i=[];G(e.positions,i,t)&&(e.positions=i,e.origin=c.addVec3(e.origin,t,t))}if(e.positions){const t=c.collapseAABB3();e.positionsDecodeMatrix=c.mat4(),c.expandAABB3Points3(t,e.positions),e.positionsCompressed=Dr(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=c.collapseAABB3();c.expandAABB3Points3(t,e.positionsCompressed),St.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=c.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=c.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Oo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Oo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new xn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new ga({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=c.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=c.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=K),this._pickable&&!1!==e.pickable&&(t|=X),this._culled&&!1!==e.culled&&(t|=W),this._clippable&&!1!==e.clippable&&(t|=J),this._collidable&&!1!==e.collidable&&(t|=Y),this._edges&&!1!==e.edges&&(t|=ee),this._xrayed&&!1!==e.xrayed&&(t|=Z),this._highlighted&&!1!==e.highlighted&&(t|=q),this._selected&&!1!==e.selected&&(t|=$),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class zA extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class ih extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ne(i,t.origin),this._targetMarker=new ne(i,t.target),this._originWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=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:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new le(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ae(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ae(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ae(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ae(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new Ae(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new Ae(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new Ae(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new Ae(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],u=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var d=0,p=s.length;de.offsetTop+(e.offsetParent&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&u(e.offsetParent));this._onCameraControlHoverSnapOrSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.left=u(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class oh{constructor(){}getMetaModel(e,t,i){_.loadJSON(e,(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){_.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){_.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class nh{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=ah(e,i);return s?t?lh(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=ah(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=lh(r,[t]),i&&(r=lh(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function ah(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=c.subVec3(o,r,[]);return c.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=c.lenVec3(c.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class hh extends Ah{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=c.vec3();return A[0]=c.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=c.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=c.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const ch=c.vec3();const uh=c.vec3(),dh=c.vec3(),ph=c.vec3(),fh=c.vec3(),gh=c.vec3();class mh extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=c.vec3(),this._eye1=c.vec3(),this._up1=c.vec3(),this._look2=c.vec3(),this._eye2=c.vec3(),this._up2=c.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const h=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?mh._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(c.subVec3(s.eye,s.look,gh),s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,ph),s.look=c.subVec3(ph,gh,dh)):this._flyingLook&&(s.look=c.lerpVec3(i,0,1,this._look1,this._look2,dh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,fh)):this._flyingEyeLookUp&&(s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,ph),s.look=c.lerpVec3(i,0,1,this._look1,this._look2,dh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,fh)),this._projection2){const t="ortho"===this._projection2?mh._easeOutExpo(e,0,1,1):mh._easeInCubic(e,0,1,1);s.customProjection.matrix=c.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class _h extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new mh(this),this._t=0,this.state=_h.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case _h.SCRUBBING:return;case _h.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=_h.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case _h.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=_h.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=_h.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=_h.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=_h.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=_h.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=_h.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=_h.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}_h.STOPPED=0,_h.SCRUBBING=1,_h.PLAYING=2,_h.PLAYING_TO=3;const vh=c.vec3(),bh=c.vec3();c.vec3();const yh=c.vec3([0,-1,0]),Bh=c.vec4([0,0,0,1]);function xh(e){if(!wh(e.width)||!wh(e.height)){const t=document.createElement("canvas");t.width=Ph(e.width),t.height=Ph(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function wh(e){return 0==(e&e-1)}function Ph(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Ch extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new $e({texture:new gs({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),p.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const Fh=c.vec3();const Eh=c.vec3();class Ih{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,h=!t||t.colorize,c=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),h){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}c&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,h=!t||t.opacity;var c=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[c]),s&&(t.edges=this.objectsEdges[c]),r&&(t.xrayed=this.objectsXrayed[c]),o&&(t.highlighted=this.objectsHighlighted[c]),n&&(t.selected=this.objectsSelected[c]),a&&(t.clippable=this.objectsClippable[c]),l&&(t.pickable=this.objectsPickable[c]),A&&(this.objectsHasColorize[c]?(Eh[0]=this.objectsColorize[3*c+0],Eh[1]=this.objectsColorize[3*c+1],Eh[2]=this.objectsColorize[3*c+2],t.colorize=Eh):t.colorize=null),h&&(t.opacity=this.objectsOpacity[c]),c++}}}class Dh extends D{constructor(e,t={}){super(e,t),this._skyboxMesh=new Gi(this,{geometry:new Lt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Qt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Bs(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}const Sh=c.vec4(),Th=c.vec4(),Rh=c.vec3(),Lh=c.vec3(),Uh=c.vec3(),Oh=c.vec4(),kh=c.vec4(),Nh=c.vec4();class Qh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=c.subVec3(e,r.eye,Rh);s=c.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=c.vec3();c.decomposeMat4(c.inverseMat4(this._scene.viewer.camera.viewMatrix,c.mat4()),t,c.vec4(),c.vec3());const i=c.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),j(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Ps(this._scene,Wi({radius:s})),this._pivotSphere=new Gi(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){c.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,c.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(j(this.getPivotPos(),this._rtcCenter,this._rtcPos),c.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Qt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=c.lookAtMat4v(e.eye,e.look,e.worldUp);c.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=c.distVec3(e.eye,i),t=c.inverseMat4(t);const s=c.transformVec3(t,this._cameraOffset),r=c.vec3();if(c.subVec3(e.eye,i,r),c.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=c.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=c.normalizeVec3(c.subVec3(e.look,e.eye,Hh)),i=c.cross3Vec3(t,e.worldUp,Vh);return c.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(c.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=c.dotVec4(n,r)/c.dotVec4(n,o),l=Gh;t.project.unproject(e,a,zh,Kh,l);const A=c.normalizeVec3(c.subVec3(l,t.eye,Hh)),h=c.addVec3(t.eye,c.mulVec3Scalar(A,i,Vh),jh);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=c.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=c.lenVec3(c.subVec3(i.look,i.eye,c.vec3())),a=this.getPivotPos();c.addVec3(o,a);let l=c.lookAtMat4v(o,a,i.worldUp);l=c.inverseMat4(l);const A=c.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],c.subVec3(i.eye,c.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Xh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=c.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Pe;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Jh=c.vec2();class Yh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,u=0,d=0,p=!1;const f=c.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],u=t[3],d=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l){const t=d-A,i=g-h,s=e.camera;if("perspective"===s.projection){const o=Math.abs(p?c.lenVec3(c.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/u,r.panDeltaY+=1.5*i*o/u}else r.panDeltaX+=.5*s.ortho.scale*(t/u),r.panDeltaY+=.5*s.ortho.scale*(i/u)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=(d-A)/o*i.dragRotationRate/2,r.rotateDeltaX+=(g-h)/u*(i.dragRotationRate/4)):(r.rotateDeltaY-=(d-A)/o*(1.5*i.dragRotationRate),r.rotateDeltaX+=(g-h)/u*(1.5*i.dragRotationRate)));A=d,h=g}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Jh);const i=Jh[0],s=Jh[1];Math.abs(i-u)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Jh,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||u))return;const d=e.aabb,p=c.getAABB3Diag(d);c.getAABB3Center(d,Zh);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*c.DEGTORAD)),g=1.1*p;ic.orthoScale=g,n?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldRight,f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):a?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldForward,f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):l?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldRight,-f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):A?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldForward,-f,qh),tc)),ic.look.set(Zh),ic.up.set(o.worldUp)):h?(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldUp,f,qh),tc)),ic.look.set(Zh),ic.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,1,$h),ec))):u&&(ic.eye.set(c.addVec3(Zh,c.mulVec3Scalar(o.worldUp,-f,qh),tc)),ic.look.set(Zh),ic.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,-1,$h)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Zh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(ic,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(ic),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class rc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),d=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||d)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=d,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",d),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=c.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=c.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class oc{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const nc=c.vec3();class ac{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer&&--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(c.lenVec3(c.subVec3(u,e.camera.eye,nc)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Ac(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Ac(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Ac(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s-window.scrollX,i[1]=e.clientY-r-window.scrollY}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const hc=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class cc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=c.vec2(),l=c.vec2(),A=c.vec2(),h=c.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(hc(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length{n.getPivoting()&&n.endPivot()}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],g=t.touches;if(t.touches.length===p){if(1===p){hc(g[0],l),c.subVec2(l,u[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];hc(t,l),hc(n,A);const a=c.geometricMeanVec2(u[0],u[1]),h=c.geometricMeanVec2(l,A),p=c.vec2();c.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=c.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(c.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(c.lenVec3(c.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=m*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/d)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,uc(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(u>-1&&h-u<325?(uc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):c.distVec2(l[0],A)<4&&(uc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:c.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:c.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Xh(this,this._configs),pivotController:new Wh(i,this._configs),panController:new Qh(i),cameraFlight:new mh(this,{duration:.5})},this._handlers=[new lc(this.scene,this._controllers,this._configs,this._states,this._updates),new cc(this.scene,this._controllers,this._configs,this._states,this._updates),new Yh(this.scene,this._controllers,this._configs,this._states,this._updates),new sc(this.scene,this._controllers,this._configs,this._states,this._updates),new rc(this.scene,this._controllers,this._configs,this._states,this._updates),new dc(this.scene,this._controllers,this._configs,this._states,this._updates),new oc(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new ac(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?bc(t):null,n=i&&i.length>0?bc(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r * Copyright (c) 2022 Niklas von Hertzen diff --git a/dist/xeokit-sdk.min.es.js b/dist/xeokit-sdk.min.es.js index f18a2f89a..e85d2a65b 100644 --- a/dist/xeokit-sdk.min.es.js +++ b/dist/xeokit-sdk.min.es.js @@ -1,4 +1,4 @@ -class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+" [MORE]"):i.push('
  • '+l+"
  • ")}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-85+"px":this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2,(e.top+e.bottom)/2];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let a=!0,l=a?Float64Array:Float32Array;const A=new l(3),h=new l(16),c=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(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 l(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new l(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.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=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.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:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new l([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new l(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 l(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],B=t[3],x=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+B*f,i[1]=v*r+b*l+y*u+B*g,i[2]=v*o+b*A+y*d+B*m,i[3]=v*n+b*h+y*p+B*_,i[4]=x*s+w*a+P*c+C*f,i[5]=x*r+w*l+P*u+C*g,i[6]=x*o+w*A+P*d+C*m,i[7]=x*n+w*h+P*p+C*_,i[8]=M*s+F*a+E*c+I*f,i[9]=M*r+F*l+E*u+I*g,i[10]=M*o+F*A+E*d+I*m,i[11]=M*n+F*h+E*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*g+A*v,i[4]=n*p+a*m+A*b,i[7]=n*f+a*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,B=s*A-o*a,x=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,F=c*m-d*f,E=u*m-d*g,I=1/(_*E-v*F+b*M+y*C-B*P+x*w);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*x-g*B+m*y)*I,t[3]=(-c*x+u*B-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*x+g*b-m*v)*I,t[7]=(h*x-u*b+d*v)*I,t[8]=(n*F-a*C+A*w)*I,t[9]=(-i*F+s*C-o*w)*I,t[10]=(p*B-f*b+m*_)*I,t[11]=(-h*B+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,c,u,p,f,g;return h=a*l,c=l*A,u=A*a,p=a*r,f=l*r,g=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*u-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*c+p,i[7]=0,i[8]=n*u+f,i[9]=n*c-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,c=s*l,u=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=c+v,i[2]=u-_,i[3]=0,i[4]=c-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=u+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],c=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-h,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(c,u),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,u),i[1]=0)),i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,c=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=c,t[9]*=c,t[10]*=c,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],c=t[1],u=t[2];if(r===h&&o===c&&n===u)return d.identityMat4();let p,f,g,m,_,v,b,y,B,x;return p=r-h,f=o-c,g=n-u,x=1/Math.sqrt(p*p+f*f+g*g),p*=x,f*=x,g*=x,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,x=Math.sqrt(m*m+_*_+v*v),x?(x=1/x,m*=x,_*=x,v*=x):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,B=p*_-f*m,x=Math.sqrt(b*b+y*y+B*B),x?(x=1/x,b*=x,y*=x,B*=x):(b=0,y=0,B=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=B,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+B*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,h),d.subVec4(r,s,c);const o=2*s[2],n=c[0],a=c[1],l=c[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=h[0]/n,i[9]=h[1]/a,i[10]=-h[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],B=e[13],x=e[14],w=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),c=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"YXZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"ZXY"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"ZYX"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"YZX"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l-A*h*c):"XZY"===t&&(i[0]=A*a*l-n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l+A*h*c),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let c;const u=i+n+h;return u>0?(c=.5/Math.sqrt(u+1),t[3]=.25/c,t[0]=(A-a)*c,t[1]=(r-l)*c,t[2]=(o-s)*c):i>n&&i>h?(c=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/c,t[0]=.25*c,t[1]=(s+o)/c,t[2]=(r+l)/c):n>h?(c=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/c,t[0]=(s+o)/c,t[1]=.25*c,t[2]=(a+A)/c):(c=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/c,t[0]=(r+l)/c,t[1]=(a+A)/c,t[2]=.25*c),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new l(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,c=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+c*-l-u*-a,i[1]=c*A+p*-a+u*-n-h*-l,i[2]=u*A+p*-l+h*-a-c*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,c=l*o,u=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+c,t[2]=f-h,t[4]=p-c,t[5]=1-(u+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],B=e[14],x=e[15];for(s=0;s{const e=new l(3),t=new l(3),i=new l(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],c=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>c?h:c,Math.abs(d.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.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 l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,h=d.MIN_DOUBLE,c=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>c&&(c=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=c,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=c);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;rc&&(c=h);return s[3]=c,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,c=n*a-r*A,u=r*l-o*a,p=Math.sqrt(h*h+c*c+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=c/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,h)=>{h=h||d.vec3();const c=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(c,p);if(f<1e-6)return null;const g=d.subVec3(o,a,s),m=d.dotVec3(g,p);if(m<0||m>f)return null;const _=d.cross3Vec3(g,c,r),v=d.dotVec3(n,_);if(v<0||m+v>f)return null;const b=d.dotVec3(u,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const h=d.subVec3(a,n,t),c=d.subVec3(l,n,i),u=d.cross3Vec3(h,c,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),h=d.subVec3(s,r,i),c=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,h),f=d.dotVec3(A,A),g=d.dotVec3(A,h),m=c*f-u*u;if(0===m)return null;const _=1/m,v=(f*p-u*g)*_,b=(c*g-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,h;const c=new Array(n.length/3);let u,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const h=new Float32Array(a.length);for(let c=0;c>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,c;const u=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),i=new l(4),s=new l(4),r=new l(4),o=new l(4);return(n,a,l,A,h,c)=>{const u=d.mulMat4(l,a,e),p=d.inverseMat4(u,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,d.transformVec4(p,i,s),d.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,d.transformVec4(p,r,o),d.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],d.subVec3(o,s,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l)=>{d.canvasPosToWorldRay(i,s,r,n,e,t),d.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,h;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;An[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{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 m={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 _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:b,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 y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.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 y.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return y.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{x.removeItem(e.id),delete I.scenes[e.id],delete B[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){w.push(e),w.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;w.length>0&&(e<0||s0&&M>0){var t=1e3/M;E+=t,C.push(t),C.length>=30&&(E-=C.shift()),m.frame.fps=Math.round(E/C.length)}for(let e in I.scenes)I.scenes[e].compile();T(e),F=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{D()}),100);const S=function(){let e=Date.now();if(M=e-F,F>0&&M>0){var t=1e3/M;E+=t,C.push(t),C.length>=30&&(E-=C.shift()),m.frame.fps=Math.round(E/C.length)}T(e),function(e){for(var t in P.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];P.sceneId=t,P.startTime=i.startTime,P.deltaTime=null!=P.prevTime?P.time-P.prevTime:0,i.fire("tick",P,!0)}P.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=B[n],s||(s=B[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(S)};function T(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}S();class R{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 R))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+y.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class N{constructor(){this.planes=[new k,new k,new k,new k,new k,new k]}}function Q(e,t,i){const s=d.mulMat4(i,t,O),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],c=s[7],u=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,c-l,g-u,b-m),e.planes[1].set(a+r,c+l,g+u,b+m),e.planes[2].set(a-o,c-A,g-p,b-_),e.planes[3].set(a+o,c+A,g+p,b+_),e.planes[4].set(a-n,c-h,g-f,b-v),e.planes[5].set(a+n,c+h,g+f,b+v)}function H(e,t){let i=N.INSIDE;const s=L,r=U;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class V extends R{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new N,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==V.PICK_MODE_INSIDE&&e!==V.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===V.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=H(this._marqueeFrustum,i.aabb)),s!==N.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,c=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,h*a,c*a,u,1e4,this._marqueeFrustumProjMat),Q(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}V.PICK_MODE_INTERSECTS=0,V.PICK_MODE_INSIDE=1;class j extends R{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const z=d.vec3(),K=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,o),o.slice()}}();function W(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function X(e,t,i,s=1e3){const r=d.getPositionsCenter(e,z),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{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&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Ae.set(this._viewPos),Ae[3]=1,d.transformPoint4(this.scene.camera.projMatrix,Ae,he);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+he[0]/he[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-he[1]/he[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 le?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]),W(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 ue{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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,i=this._wire.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)";var s=this._wireClickable.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)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class de{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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 i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class pe{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 i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-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 fe=d.vec3(),ge=d.vec3();class me extends R{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 i=this.plugin.viewer.scene;this._originMarker=new ce(i,t.origin),this._cornerMarker=new ce(i,t.corner),this._targetMarker=new ce(i,t.target),this._originWorld=d.vec3(),this._cornerWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ue(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ue(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new pe(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),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=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>u||f>u||g>u)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);d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,c=t.length;h{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:const s=t.getBoundingClientRect(),r=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,n=s.left+r,a=s.top+o;this.markerDiv.style.left=n+i[0]-5+"px",this.markerDiv.style.top=a+i[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class be extends G{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new ve(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new me(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{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||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[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 i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}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 i=e[t];this.setField(t,i)}}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 Be=d.vec3(),xe=d.vec3(),we=d.vec3();class Pe extends G{constructor(e,t){super("Annotations",e),this._labelHTML=t.labelHTML||"
",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){var t,i;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){const s=e.pickResult;if(s.worldPos&&s.worldNormal){const e=d.normalizeVec3(s.worldNormal,Be),r=d.mulVec3Scalar(e,this._surfaceOffset,xe);t=d.addVec3(s.worldPos,r,we),i=s.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var s=null;e.markerElementId&&((s=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var r=null;e.labelElementId&&((r=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const o=new ye(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:s,labelElement:r,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:y.apply(e.values,y.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[o.id]=o,o.on("destroyed",(()=>{delete this.annotations[o.id],this.fire("annotationDestroyed",o.id)})),this.fire("annotationCreated",o.id),o}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;t
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Me=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Fe extends R{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Ce(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-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Ie.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Ie.FS_MAX_FLOAT_PRECISION="mediump":Ie.FS_MAX_FLOAT_PRECISION="lowp":Ie.FS_MAX_FLOAT_PRECISION="mediump",Ie.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Ie.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Ie.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Ie.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Ie.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ie.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Ie.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Ie.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Ie.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Ie.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Ie.SUPPORTED_EXTENSIONS[e]=!0})))}class Se{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Te{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function ke(e){console.error(e.join("\n"))}class Ne{constructor(e,t){this.id=Ue.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 Te(e,e.VERTEX_SHADER,Oe(this.source.vertex)),this._fragmentShader=new Te(e,e.FRAGMENT_SHADER,Oe(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ke(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ke(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ke(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ke(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void ke(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.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 He{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.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-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new He(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new He(this._scene,e.origin),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ne(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,c=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;ze[0]=o,ze[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,c),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,ze),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ne(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Qe(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Qe(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Qe(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const We=new Float32Array($e(17,[0,1])),Xe=new Float32Array($e(17,[1,0])),Je=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(qe(s,t));return i}(17,4)),Ye=new Float32Array(2);class Ze{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 Ne(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Qe(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Qe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Qe(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),Ye[0]=n,Ye[1]=a,s.uniform2fv(this._uViewport,Ye),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Xe):s.uniform2fv(this._uSampleOffsets,We),s.uniform1fv(this._uSampleWeights,Je);const c=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,c,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function qe(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function $e(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class et{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class tt{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new et(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function it(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const st=function(t,i){i=i||{};const s=new Ee(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},c=!0,u=!0,p=!0,f=!0,g=!0,_=!0,v=!0,b=!0;const y=new tt(t);let B=!1;const x=new Ke(t),w=new Ze(t);function P(){c&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),c=!1,u=!0),u&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),u=!1,p=!0),p&&function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||j>0||k>0||N>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||N>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),N>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||z>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),z>0)for(S=0;S0)for(S=0;S0||W>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||J>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),J>0)for(S=0;S0)for(S=0;S0||Z>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Z>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=u.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let D=null,S=null,T=null,R=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),R=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;S=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),D=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===B&&null==D)return null;let L=null;null!==D&&(L=t.camera.projectWorldPos(D));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===R,h.snappedToVertex="vertex"===R,h.worldPos=D,h.worldNormal=S,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=L||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Ge(t,y),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const ot=new e({});class nt{constructor(e){this.id=ot.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ot.removeItem(this.id)}}class at extends R{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new nt({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class lt extends R{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class At extends R{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ht extends R{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.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(){d.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&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class ct extends R{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.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&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ut=d.vec3(),dt=d.vec3(),pt=d.vec3(),ft=d.vec3(),gt=d.vec3(),mt=d.vec3(),_t=d.vec4(),vt=d.vec4(),bt=d.vec4(),yt=d.mat4(),Bt=d.mat4(),xt=d.vec3(),wt=d.vec3(),Pt=d.vec3(),Ct=d.vec3();class Mt extends R{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new nt({deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new lt(this),this._ortho=new At(this),this._frustum=new ht(this),this._customProjection=new ct(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.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?(d.subVec3(this._eye,this._look,xt),d.normalizeVec3(xt,wt),d.mulVec3Scalar(wt,1e3,Pt),d.addVec3(this._look,Pt,Ct),t=Ct):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Bt),d.mulMat4(e.deviceMatrix,Bt,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.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=d.subVec3(this._eye,this._look,ut);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yt),t=d.transformPoint3(yt,t,dt),this.eye=d.addVec3(this._look,t,pt),this.up=d.transformPoint3(yt,this._up,ft)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,ut);const i=d.cross3Vec3(d.normalizeVec3(t,dt),d.normalizeVec3(this._up,pt));d.rotationMat4v(.0174532925*e,i,yt),t=d.transformPoint3(yt,t,ft),this.up=d.transformPoint3(yt,this._up,gt),this.eye=d.addVec3(t,this._look,mt)}yaw(e){let t=d.subVec3(this._look,this._eye,ut);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yt),t=d.transformPoint3(yt,t,dt),this.look=d.addVec3(t,this._eye,pt),this._gimbalLock&&(this.up=d.transformPoint3(yt,this._up,ft))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,ut);const i=d.cross3Vec3(d.normalizeVec3(t,dt),d.normalizeVec3(this._up,pt));d.rotationMat4v(.0174532925*e,i,yt),this.up=d.transformPoint3(yt,this._up,mt),t=d.transformPoint3(yt,t,ft),this.look=d.addVec3(t,this._eye,gt)}pan(e){const t=d.subVec3(this._eye,this._look,ut),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,dt));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,pt),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,ft),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,gt),this.look=d.addVec3(this._look,i,mt)}zoom(e){const t=d.subVec3(this._eye,this._look,ut),i=Math.abs(d.lenVec3(t,dt)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,pt);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),ft)}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=d.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 d.lenVec3(d.subVec3(this._look,this._eye,ut))}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=_t,i=vt,s=bt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Ft extends R{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Et extends Ft{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new nt({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new et(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class It extends Ft{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Dt extends R{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}var St=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const Tt=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/h,l/h,A/h],t),d.mulMat4(e,t,s),s}}();var Rt=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Ot(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function kt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Nt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Ut(e,a,"floor","ceil"),s=Ot(i),o=kt(e,a,s),o>n&&(r=i,n=o),i=Ut(e,a,"ceil","ceil"),s=Ot(i),o=kt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Qt=m.memory,Ht=d.AABB3();class Vt extends Dt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new nt({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Nt.getPositionsBounds(t.positions),s=Nt.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Nt.getUVBounds(t.uv),s=Nt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Nt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Qt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Qt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Qt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new Qe(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Qt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Qt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Qe(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Qt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=St(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Qt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Qt.positions+=this._pickTrianglePositionsBuf.numItems,Qt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Nt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Nt.getPositionsBounds(e),s=Nt.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Nt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Nt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,Ht,this._state.positionsDecodeMatrix),d.AABB3ToOBB3(Ht,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Qt.meshes--}}function jt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Gt extends R{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const zt={opaque:0,mask:1,blend:2},Kt=["opaque","mask","blend"];class Wt extends Gt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new nt({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=zt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Kt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Xt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Jt extends Gt{get type(){return"EmphasisMaterial"}get presets(){return Xt}constructor(e,t={}){super(e,t),this._state=new nt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Xt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Xt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Zt extends Gt{get type(){return"EdgeMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new nt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const qt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class $t extends R{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return qt}set units(e){e||(e="meters");qt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class ei extends R{constructor(e,t={}){super(e,t),this._supported=Ie.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const ti={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class ii extends Gt{get type(){return"PointsMaterial"}get presets(){return ti}constructor(e,t={}){super(e,t),this._state=new nt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=ti[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ti).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const si={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ri extends Gt{get type(){return"LinesMaterial"}get presets(){return si}constructor(e,t={}){super(e,t),this._state=new nt({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=si[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(si).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function oi(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new st(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+y.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],y.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=oi(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=oi(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ai=1e3,li=1001,Ai=1002,hi=1003,ci=1004,ui=1004,di=1005,pi=1005,fi=1006,gi=1007,mi=1007,_i=1008,vi=1008,bi=1009,yi=1010,Bi=1011,xi=1012,wi=1013,Pi=1014,Ci=1015,Mi=1016,Fi=1017,Ei=1018,Ii=1020,Di=1021,Si=1022,Ti=1023,Ri=1024,Li=1025,Ui=1026,Oi=1027,ki=1028,Ni=1029,Qi=1030,Hi=1031,Vi=1033,ji=33776,Gi=33777,zi=33778,Ki=33779,Wi=35840,Xi=35841,Ji=35842,Yi=35843,Zi=36196,qi=37492,$i=37496,es=37808,ts=37809,is=37810,ss=37811,rs=37812,os=37813,ns=37814,as=37815,ls=37816,As=37817,hs=37818,cs=37819,us=37820,ds=37821,ps=36492,fs=3e3,gs=3001,ms=1e4,_s=10001,vs=10002,bs=10003,ys=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=ws(e),u=s.getNumAllocatedSectionPlanes()>0,d=xs(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=ws(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=xs(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Bs[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Bs[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Bs[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Bs[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Bs[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Bs[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Es{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Is=new e({}),Ds=d.vec3(),Ss=function(e,t){this.id=Is.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Es(t),this._allocate(t)},Ts={};Ss.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ts[t];return i||(i=new Ss(t,e),Ts[t]=i,m.memory.programs++),i._useCount++,i},Ss.prototype.put=function(){0==--this._useCount&&(Is.removeItem(this.id),this._program&&this._program.destroy(),delete Ts[this._hash],m.memory.programs--)},Ss.prototype.webglContextRestored=function(){this._program=null},Ss.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ls=new e({}),Us=d.vec3(),Os=function(e,t){this.id=Ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Rs(t),this._allocate(t)},ks={};Os.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ks[t];return i||(i=new Os(t,e),ks[t]=i,m.memory.programs++),i._useCount++,i},Os.prototype.put=function(){0==--this._useCount&&(Ls.removeItem(this.id),this._program&&this._program.destroy(),delete ks[this._hash],m.memory.programs--)},Os.prototype.webglContextRestored=function(){this._program=null},Os.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Qs=d.vec3(),Hs=function(e,t){this._hash=e,this._shaderSource=new Ns(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Vs={};Hs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Vs[t];if(!i){if(i=new Hs(t,e),i.errors)return console.log(i.errors.join("\n")),null;Vs[t]=i,m.memory.programs++}return i._useCount++,i},Hs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Vs[this._hash],m.memory.programs--)},Hs.prototype.webglContextRestored=function(){this._program=null},Hs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Hs.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ne(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Gs=d.vec3(),zs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new js(t),this._allocate(t)},Ks={};zs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ks[t];if(!i){if(i=new zs(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ks[t]=i,m.memory.programs++}return i._useCount++,i},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ks[this._hash],m.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Xs=d.vec3(),Js=function(e,t){this._hash=e,this._shaderSource=new Ws(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ys={};Js.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ys[t];if(!i){if(i=new Js(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ys[t]=i,m.memory.programs++}return i._useCount++,i},Js.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ys[this._hash],m.memory.programs--)},Js.prototype.webglContextRestored=function(){this._program=null},Js.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const qs=function(e,t){this._hash=e,this._shaderSource=new Zs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},$s={};qs.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=$s[i];if(!s){if(s=new qs(i,e),s.errors)return console.log(s.errors.join("\n")),null;$s[i]=s,m.memory.programs++}return s._useCount++,s},qs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete $s[this._hash],m.memory.programs--)},qs.prototype.webglContextRestored=function(){this._program=null},qs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},qs.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ne(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ur=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),B=d.vec3(),x=d.vec3(),w=d.vec3(),P=d.vec3(),C=d.vec3(),M=d.vec3(),F=d.vec3(),E=d.vec3(),I=d.vec3();return function(D,S,T,R){var L=R.primIndex;if(null!=L&&L>-1){const N=D.geometry._state,Q=D.scene,H=Q.camera,V=Q.canvas;if("triangles"===N.primitiveName){R.primitive="triangle";const Q=L,j=N.indices,G=N.positions;let z,W,X;if(j){var U=j[Q+0],O=j[Q+1],k=j[Q+2];o[0]=U,o[1]=O,o[2]=k,R.indices=o,z=3*U,W=3*O,X=3*k}else z=3*Q,W=z+3,X=W+3;if(i[0]=G[z+0],i[1]=G[z+1],i[2]=G[z+2],s[0]=G[W+0],s[1]=G[W+1],s[2]=G[W+2],r[0]=G[X+0],r[1]=G[X+1],r[2]=G[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(Nt.decompressPosition(i,e,i),Nt.decompressPosition(s,e,s),Nt.decompressPosition(r,e,r))}R.canvasPos?d.canvasPosToLocalRay(V.canvas,D.origin?K(S,D.origin):S,T,D.worldMatrix,R.canvasPos,e,t):R.origin&&R.direction&&d.worldRayToLocalRay(D.worldMatrix,R.origin,R.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),R.localPos=n,R.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,d.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],R.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),R.worldPos=a,d.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],R.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),R.bary=A;const J=N.normals;if(J){if(N.compressGeometry){const e=3*U,t=3*O,i=3*k;Nt.decompressNormal(J.subarray(e,e+2),h),Nt.decompressNormal(J.subarray(t,t+2),c),Nt.decompressNormal(J.subarray(i,i+2),u)}else h[0]=J[z],h[1]=J[z+1],h[2]=J[z+2],c[0]=J[W],c[1]=J[W+1],c[2]=J[W+2],u[0]=J[X],u[1]=J[X+1],u[2]=J[X+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(h,A[0],b),d.mulVec3Scalar(c,A[1],y),B),d.mulVec3Scalar(u,A[2],x),w);R.worldNormal=d.normalizeVec3(d.transformVec3(D.worldNormalMatrix,e,P))}const Y=N.uv;if(Y){if(p[0]=Y[2*U],p[1]=Y[2*U+1],f[0]=Y[2*O],f[1]=Y[2*O+1],g[0]=Y[2*k],g[1]=Y[2*k+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(Nt.decompressUV(p,e,p),Nt.decompressUV(f,e,f),Nt.decompressUV(g,e,g))}R.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),F),d.mulVec2Scalar(g,A[2],E),I)}}}}}();function dr(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],_=[],v=[];let b,B,x,w,P,C,M,F,E,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(P=t-b*f,C=c-b*u,B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),m.push(P*x),m.push(S),m.push(P*w),_.push(B*p),_.push(1*b/o),g.push(P*x+l),g.push(C+A),g.push(P*w+h);for(b=0;b0){for(E=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(t*x),m.push(1),m.push(t*w),_.push(I),_.push(D),g.push(t*x+l),g.push(c+A),g.push(t*w+h);for(B=0;B0){for(E=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(i*x),m.push(-1),m.push(i*w),_.push(I),_.push(D),g.push(i*x+l),g.push(0-c+A),g.push(i*w+h);for(B=0;B":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function gr(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,_=(l||"").split("\n"),v=0,b=0,B=.04,x=0;x<_.length;x++){A=0,c=(h=_[x]).length;for(var w=0;w0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=Ur(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=Ur(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=Ur(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Qr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Qr(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Ur(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Ur(i,this.magFilter)));const a=Ur(i,this.format,this.encoding),l=Ur(i,this.type),A=Nr(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Gr extends R{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new nt({texture:new kr({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new kr({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Hr(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=Hr(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}class zr extends R{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new nt({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const Kr=m.memory,Wr=d.AABB3();class Xr extends Dt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new nt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Nt.getPositionsBounds(t.positions),o=Nt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new Qe(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Kr.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,Wr,i.positionsDecodeMatrix),d.AABB3ToOBB3(Wr,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new Qe(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Kr.colors+=i.colorsBuf.numItems}if(t.uv){const e=Nt.getUVBounds(t.uv),r=Nt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new Qe(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Kr.uvs+=i.uvBuf.numItems}if(t.normals){const e=Nt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new Qe(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Kr.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Kr.indices+=i.indicesBuf.numItems;const o=St(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Kr.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Kr.meshes--}}var Jr={};function Yr(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=Jr.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function Zr(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=Jr.parse.fromOBJ(e),n=Jr.edit.unwrap(o.i_verts,o.c_verts,3),a=Jr.edit.unwrap(o.i_norms,o.c_norms,3),l=Jr.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function qr(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function $r(e={}){return qr({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function eo(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}function to(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,B,x,w,P,C,M,F=0,E=0;for(b=0;b65535?Uint32Array:Uint16Array)(c*u*6);for(b=0;b360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],c=[],u=[],p=[];let f,g,m,_,v,b,B,x,w,P,C,M;for(x=0;x<=r;x++)for(B=0;B<=s;B++)f=B/s*o,g=.785398+x/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),_=(t+i*Math.cos(g))*Math.sin(f),v=i*Math.sin(g),h.push(m+a),h.push(_+l),h.push(v+A),u.push(1-B/s),u.push(x/r),b=d.normalizeVec3(d.subVec3([m,_,v],[a,l,A],[]),[]),c.push(b[0]),c.push(b[1]),c.push(b[2]);for(x=1;x<=r;x++)for(B=1;B<=s;B++)w=(s+1)*x+B-1,P=(s+1)*(x-1)+B-1,C=(s+1)*(x-1)+B,M=(s+1)*x+B,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return y.apply(e,{positions:h,normals:c,uv:u,indices:p})}function so(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e[...e])).flat();return so({id:e.id,points:t})}Jr.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},Jr.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(Jr.parse._buffToStr(e));window.location.href=i},Jr.clone=function(e){return JSON.parse(JSON.stringify(e))},Jr.bin={},Jr.bin.f=new Float32Array(1),Jr.bin.fb=new Uint8Array(Jr.bin.f.buffer),Jr.bin.rf=function(e,t){for(var i=Jr.bin.f,s=Jr.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Jr.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Jr.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Jr.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Jr.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Jr.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Jr.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Jr.parse={},Jr.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class oo extends R{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new Gr(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Fr(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new cr(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Vt(this,to({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Wt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const no=d.OBB3(),ao=d.OBB3(),lo=d.OBB3();class Ao{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(d.AABB3ToOBB3(this._aabbLocal,no),this.transform?(d.transformOBB3(this.transform.worldMatrix,no,ao),d.transformOBB3(this.model.worldMatrix,ao,lo),d.OBB3ToAABB3(lo,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,no,ao),d.OBB3ToAABB3(ao,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const ho=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let co=0;const uo={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},po=new Float32Array([1,1,1,1]),fo=new Float32Array([0,0,0,1]),go=d.vec4(),mo=d.vec3(),_o=d.vec3(),vo=d.mat4();class bo{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;go[0]=i,go[1]=s,go[2]=t.blendCutoff,go[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,go),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===uo[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===uo[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===uo[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?fo:po)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,m.memory.programs--}}class yo extends bo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Bo extends yo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class xo extends yo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = vColor;"),o.push("}"),o}}class Po extends yo{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class Co extends Po{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Mo extends Po{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Fo extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Eo extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Io extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Do extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class So extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class To extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Ro extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class Lo extends yo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Oo extends yo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Go=d.vec3(),zo=d.vec3(),Ko=d.vec3(),Wo=d.vec3(),Xo=d.mat4();class Jo extends bo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Go;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=zo;if(l){const e=Ko;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Xo),m=Wo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Yo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new wo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Fo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Eo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new jo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Jo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Bo(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Bo(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new xo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new xo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Oo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Oo(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Lo(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Lo(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new wo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new So(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new To(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Co(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Mo(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fo(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Io(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Uo(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Eo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Do(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ro(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Jo(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new jo(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Zo={};let qo=65536,$o=5e6;class en{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),qo=e}get maxDataTextureHeight(){return qo}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),$o=e}get maxGeometryBatchSize(){return $o}}const tn=new en;class sn{constructor(){this.maxVerts=tn.maxGeometryBatchSize,this.maxIndices=3*tn.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const rn=d.mat4(),on=d.mat4();function nn(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,c=65525,u=c/l,p=c/A,f=c/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function An(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const hn=d.mat4(),cn=d.mat4(),un=d.vec4([0,0,0,1]),dn=d.vec3(),pn=d.vec3(),fn=d.vec3(),gn=d.vec3(),mn=d.vec3(),_n=d.vec3(),vn=d.vec3();class bn{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Zo[t];return i||(i=new Yo(e),Zo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Zo[t],i._destroy()}))),i}(e.model.scene),this._buffer=new sn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new nt({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=hn;m?d.inverseMat4(d.transposeMat4(m,cn),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,c,u=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;ch&&(l=n,h=A),n=ln(p,"floor","ceil"),a=An(n),A=o(p,a),A>h&&(l=n,h=A),n=ln(p,"ceil","ceil"),a=An(n),A=o(p,a),A>h&&(l=n,h=A),s[r+c+0]=l[0],s[r+c+1]=l[1],s[r+c+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):nn(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new Qe(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Nt.getUVBounds(i.uv),r=Nt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new Qe(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Qe(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class yn extends bo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Bn extends yn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class xn extends yn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Pn extends yn{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Cn extends Pn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Mn extends Pn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Fn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class En extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class In extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Dn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Sn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class Tn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Rn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ln={3e3:"linearToLinear",3001:"sRGBToLinear"};class Un extends yn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Ln[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Ln[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class kn extends yn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const zn=d.vec3(),Kn=d.vec3(),Wn=d.vec3(),Xn=d.vec3(),Jn=d.mat4();class Yn extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=zn;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Kn;if(l){const e=d.transformPoint3(h,l,Wn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Jn),m=Xn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Zn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new wn(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Fn(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new En(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Gn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Yn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Bn(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Bn(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new xn(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new xn(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Un(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Un(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new kn(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new kn(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new wn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Sn(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Tn(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Cn(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Mn(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fn(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new In(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new On(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new En(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Dn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Rn(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Gn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Yn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const qn={};const $n=new Uint8Array(4),ea=new Float32Array(1),ta=d.vec4([0,0,0,1]),ia=new Float32Array(3),sa=d.vec3(),ra=d.vec3(),oa=d.vec3(),na=d.vec3(),aa=d.vec3(),la=d.vec3(),Aa=d.vec3(),ha=new Float32Array(4);class ca{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=qn[t];return i||(i=new Zn(e),qn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete qn[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new nt({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Qe(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Qe(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new Qe(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Qe(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Qe(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Qe(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";$n[0]=t[0],$n[1]=t[1],$n[2]=t[2],$n[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData($n,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Z),r=!!(t&ie),o=!!(t&se),n=!!(t&re),a=!!(t&oe),l=!!(t&$),A=!!(t&q);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?uo.NOT_RENDERED:i?uo.COLOR_TRANSPARENT:uo.COLOR_OPAQUE,c=!s||A?uo.NOT_RENDERED:n?uo.SILHOUETTE_SELECTED:o?uo.SILHOUETTE_HIGHLIGHTED:r?uo.SILHOUETTE_XRAYED:uo.NOT_RENDERED;let u=0;u=!s||A?uo.NOT_RENDERED:n?uo.EDGES_SELECTED:o?uo.EDGES_HIGHLIGHTED:r?uo.EDGES_XRAYED:a?i?uo.EDGES_COLOR_TRANSPARENT:uo.EDGES_COLOR_OPAQUE:uo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?uo.PICK:uo.NOT_RENDERED)<<12,d|=(t&ee?1:0)<<16,ea[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(ea,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ia[0]=t[0],ia[1]=t[1],ia[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(ia,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],c=ta,u=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&d.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ua extends bo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class da extends ua{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class pa extends ua{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const fa=d.vec3(),ga=d.vec3(),ma=d.vec3(),_a=d.vec3(),va=d.mat4();class ba extends bo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=fa;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ga;if(l){const e=ma;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,va),m=_a,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ya=d.vec3(),Ba=d.vec3(),xa=d.vec3(),wa=d.vec3(),Pa=d.mat4();class Ca extends bo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ya;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ba;if(l){const e=xa;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Pa),m=wa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ma{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new da(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pa(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ba(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ca(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Fa={};class Ea{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class Ia{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Fa[t];return i||(i=new Ma(e),Fa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Fa[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Ea(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new nt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=nn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class Ta extends Da{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Ra=d.vec3(),La=d.vec3(),Ua=d.vec3();d.vec3();const Oa=d.mat4();class ka extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ra;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=La;if(l){const e=d.transformPoint3(h,l,Ua);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Oa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Na=d.vec3(),Qa=d.vec3(),Ha=d.vec3();d.vec3();const Va=d.mat4();class ja extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Na;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Qa;if(l){const e=d.transformPoint3(h,l,Ha);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Va),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ga{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new ka(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ja(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Sa(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ta(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ka(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ja(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const za={};const Ka=new Uint8Array(4),Wa=new Float32Array(1),Xa=new Float32Array(3),Ja=new Float32Array(4);class Ya{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=za[t];return i||(i=new Ga(e),za[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete za[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new nt({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Qe(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new Qe(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new Qe(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Qe(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ka[0]=t[0],Ka[1]=t[1],Ka[2]=t[2],Ka[3]=t[3],this._state.colorsBuf.setData(Ka,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Z),r=!!(t&ie),o=!!(t&se),n=!!(t&re),a=!!(t&oe),l=!!(t&$),A=!!(t&q);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?uo.NOT_RENDERED:i?uo.COLOR_TRANSPARENT:uo.COLOR_OPAQUE,c=!s||A?uo.NOT_RENDERED:n?uo.SILHOUETTE_SELECTED:o?uo.SILHOUETTE_HIGHLIGHTED:r?uo.SILHOUETTE_XRAYED:uo.NOT_RENDERED;let u=0;u=!s||A?uo.NOT_RENDERED:n?uo.EDGES_SELECTED:o?uo.EDGES_HIGHLIGHTED:r?uo.EDGES_XRAYED:a?i?uo.EDGES_COLOR_TRANSPARENT:uo.EDGES_COLOR_OPAQUE:uo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?uo.PICK:uo.NOT_RENDERED)<<12,d|=(t&ee?255:0)<<16,Wa[0]=d,this._state.flagsBuf.setData(Wa,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Xa[0]=t[0],Xa[1]=t[1],Xa[2]=t[2],this._state.offsetsBuf.setData(Xa,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Ja[0]=t[0],Ja[1]=t[4],Ja[2]=t[8],Ja[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ja,i),Ja[0]=t[1],Ja[1]=t[5],Ja[2]=t[9],Ja[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ja,i),Ja[0]=t[2],Ja[1]=t[6],Ja[2]=t[10],Ja[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ja,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,uo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,uo.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Za extends bo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class qa extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class $a extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class el extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class tl extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class il extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const sl=d.vec3(),rl=d.vec3(),ol=d.vec3(),nl=d.vec3(),al=d.mat4();class ll extends bo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=sl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=rl;if(l){const e=ol;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,al),m=nl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Al=d.vec3(),hl=d.vec3(),cl=d.vec3(),ul=d.vec3(),dl=d.mat4();class pl extends bo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Al;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=hl;if(l){const e=cl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,dl),m=ul,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class fl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new qa(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new $a(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new el(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new tl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new il(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ll(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new pl(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const gl={};class ml{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class _l{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=gl[t];return i||(i=new fl(e),gl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete gl[t],i._destroy()}))),i}(e.model.scene),this._buffer=new ml(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new nt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=nn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class yl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Bl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class xl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class wl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Pl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class Cl extends vl{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ml=d.vec3(),Fl=d.vec3(),El=d.vec3();d.vec3();const Il=d.mat4();class Dl extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ml;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Fl;if(l){const e=d.transformPoint3(h,l,El);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Il),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Sl=d.vec3(),Tl=d.vec3(),Rl=d.vec3();d.vec3();const Ll=d.mat4();class Ul extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Sl;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Tl;if(l){const e=d.transformPoint3(h,l,Rl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Ll),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ol{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new bl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new yl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Pl(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Bl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new xl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new wl(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Cl(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Dl(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ul(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const kl={};const Nl=new Uint8Array(4),Ql=new Float32Array(1),Hl=new Float32Array(3),Vl=new Float32Array(4);class jl{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=kl[t];return i||(i=new Ol(e),kl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete kl[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new nt({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new Qe(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new Qe(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new Qe(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Nl[0]=t[0],Nl[1]=t[1],Nl[2]=t[2],this._state.colorsBuf.setData(Nl,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Z),r=!!(t&ie),o=!!(t&se),n=!!(t&re),a=!!(t&oe),l=!!(t&$),A=!!(t&q);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?uo.NOT_RENDERED:i?uo.COLOR_TRANSPARENT:uo.COLOR_OPAQUE,c=!s||A?uo.NOT_RENDERED:n?uo.SILHOUETTE_SELECTED:o?uo.SILHOUETTE_HIGHLIGHTED:r?uo.SILHOUETTE_XRAYED:uo.NOT_RENDERED;let u=0;u=!s||A?uo.NOT_RENDERED:n?uo.EDGES_SELECTED:o?uo.EDGES_HIGHLIGHTED:r?uo.EDGES_XRAYED:a?i?uo.EDGES_COLOR_TRANSPARENT:uo.EDGES_COLOR_OPAQUE:uo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?uo.PICK:uo.NOT_RENDERED)<<12,d|=(t&ee?255:0)<<16,Ql[0]=d,this._state.flagsBuf.setData(Ql,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Hl[0]=t[0],Hl[1]=t[1],Hl[2]=t[2],this._state.offsetsBuf.setData(Hl,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Vl[0]=t[0],Vl[1]=t[4],Vl[2]=t[8],Vl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Vl,i),Vl[0]=t[1],Vl[1]=t[5],Vl[2]=t[9],Vl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Vl,i),Vl[0]=t[2],Vl[1]=t[6],Vl[2]=t[10],Vl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Vl,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,uo.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,uo.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,uo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,uo.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Gl=d.vec3(),zl=d.vec3(),Kl=d.mat4();class Wl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Gl;if(g){const t=d.transformPoint3(c,A,zl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,Kl)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Xl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wl(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Jl={};class Yl{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Zl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class ql{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const $l={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify($l,null,4));let e=0;Object.keys($l).forEach((t=>{t.startsWith("size")&&(e+=$l[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/$l.totalLines).toFixed(2)}`);let t={};Object.keys($l).forEach((i=>{i.startsWith("size")&&(t[i]=`${($l[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class eA{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);$l.sizeDataColorsAndFlags+=l.byteLength,$l.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);$l.sizeDataTextureOffsets+=r.byteLength,$l.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);$l.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Yl,this._dataTextureState=new Zl,this._dataTextureGenerator=new eA,this._state=new nt({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&$l.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*iA||t+r>4096*iA)&&$l.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*iA&&t+r<=4096*iA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;$l.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,$l.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||aA),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,$l.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,$l.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,$l.totalLines32Bits+=t.numLines),$l.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,rA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,rA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,rA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,oA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,sA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const AA=d.vec3(),hA=d.vec3(),cA=d.vec3();d.vec3();const uA=d.vec4(),dA=d.mat4();class pA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=AA;if(g){const t=d.transformPoint3(c,A,hA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,dA),f=cA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const fA=new Float32Array([1,1,1]),gA=d.vec3(),mA=d.vec3(),_A=d.vec3();d.vec3();const vA=d.mat4();class bA{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=gA;if(A){const t=mA;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,vA),g=_A,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===uo.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,fA);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const yA=new Float32Array([0,0,0,1]),BA=d.vec3(),xA=d.vec3();d.vec3();const wA=d.mat4();class PA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=BA;if(g){const t=d.transformPoint3(c,A,xA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,wA)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===uo.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,yA);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 CA=d.vec3(),MA=d.vec3(),FA=d.mat4();class EA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=CA;if(g){const t=d.transformPoint3(c,A,MA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,FA)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 IA=d.vec3(),DA=d.vec3(),SA=d.vec3(),TA=d.mat4();class RA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=IA;if(g){const t=d.transformPoint3(c,A,DA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(o.viewMatrix,e,TA),f=SA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const LA=d.vec3(),UA=d.vec3(),OA=d.vec3();d.vec3();const kA=d.mat4();class NA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=LA;if(A){const e=UA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=K(p,t,kA),g=OA,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 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 QA=d.vec3(),HA=d.vec3(),VA=d.vec3(),jA=d.vec3();d.vec3();const GA=d.mat4();class zA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=QA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=HA;if(v){const e=d.transformPoint3(c,A,VA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,GA),_=jA,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(x,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(x,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(x,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const KA=d.vec3(),WA=d.vec3(),XA=d.vec3(),JA=d.vec3();d.vec3();const YA=d.mat4();class ZA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=KA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=WA;if(v){const e=XA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,YA),_=JA,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qA=d.vec3(),$A=d.vec3(),eh=d.vec3();d.vec3();const th=d.mat4();class ih{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=qA;if(A){const t=$A;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,th),g=eh,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sh=d.vec3(),rh=d.vec3(),oh=d.vec3();d.vec3();const nh=d.mat4();class ah{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=sh;if(g){const t=d.transformPoint3(c,A,rh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,nh),f=oh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const lh=d.vec3(),Ah=d.vec3(),hh=d.vec3();d.vec3();const ch=d.mat4();class uh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=lh;if(g){const t=Ah;d.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=K(u,e,ch),f=hh,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Ie.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&&Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dh=d.vec3(),ph=d.vec3(),fh=d.vec3();d.vec3(),d.vec4();const gh=d.mat4();class mh{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=dh;if(g){const t=d.transformPoint3(c,A,ph);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,gh),f=fh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class _h{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new bA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new RA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new NA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new mh(this._scene)),this._snapRenderer||(this._snapRenderer=new zA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new ZA(this._scene)),this._snapRenderer||(this._snapRenderer=new zA(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new pA(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new pA(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new bA(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ah(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new uh(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new PA(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new EA(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new RA(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new mh(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new mh(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new NA(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new zA(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ZA(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ih(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const vh={};class bh{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class yh{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Bh={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Bh,null,4));let e=0;Object.keys(Bh).forEach((t=>{t.startsWith("size")&&(e+=Bh[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Bh.totalPolygons).toFixed(2)}`);let t={};Object.keys(Bh).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Bh[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class xh{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Bh.sizeDataColorsAndFlags+=h.byteLength,Bh.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Bh.sizeDataTextureOffsets+=r.byteLength,Bh.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Bh.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete vh[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new bh,this._dtxState=new yh,this._dtxTextureFactory=new xh,this._state=new nt({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Bh.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*Ph||t+r>4096*Ph)&&Bh.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Ph&&t+r<=4096*Ph}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Bh.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Bh.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Bh.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||Ih),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Bh.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Bh.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Bh.totalPolygons32Bits+=t.numTriangles),Bh.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Bh.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Bh.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Bh.totalEdges32Bits+=t.numEdges),Bh.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Mh)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,Mh))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Mh))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Fh))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ch))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,uo.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,uo.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,uo.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,uo.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,uo.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,uo.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,uo.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,uo.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,uo.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,uo.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,uo.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class Sh{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class Th{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Rh={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Lh{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==kh[e])return void kh[e].push({onLoad:t,onProgress:i,onError:s});kh[e]=[],kh[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=kh[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{Rh.add(e,t);const i=kh[e];delete kh[e];for(let e=0,s=i.length;e{const i=kh[e];if(void 0===i)throw this.manager.itemError(e),t;delete kh[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Qh{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Hh=0;class Vh{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Qh,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Nh;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new Nh;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=Vh.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(Vh.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Vh.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Vh.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),Hh>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Hh++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Hh--}}Vh.BasisFormat={ETC1S:0,UASTC_4x4:1},Vh.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},Vh.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},Vh.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete jh[t],i.destroy()}))),i} +class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+" [MORE]"):i.push('
  • '+l+"
  • ")}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-85+"px":this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2,(e.top+e.bottom)/2];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let a=!0,l=a?Float64Array:Float32Array;const A=new l(3),h=new l(16),c=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(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 l(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new l(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.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=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.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:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new l([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new l(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 l(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],B=t[3],x=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],D=t[12],S=t[13],T=t[14],R=t[15];return i[0]=v*s+b*a+y*c+B*f,i[1]=v*r+b*l+y*u+B*g,i[2]=v*o+b*A+y*d+B*m,i[3]=v*n+b*h+y*p+B*_,i[4]=x*s+w*a+P*c+C*f,i[5]=x*r+w*l+P*u+C*g,i[6]=x*o+w*A+P*d+C*m,i[7]=x*n+w*h+P*p+C*_,i[8]=M*s+F*a+E*c+I*f,i[9]=M*r+F*l+E*u+I*g,i[10]=M*o+F*A+E*d+I*m,i[11]=M*n+F*h+E*p+I*_,i[12]=D*s+S*a+T*c+R*f,i[13]=D*r+S*l+T*u+R*g,i[14]=D*o+S*A+T*d+R*m,i[15]=D*n+S*h+T*p+R*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*g+A*v,i[4]=n*p+a*m+A*b,i[7]=n*f+a*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,B=s*A-o*a,x=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,F=c*m-d*f,E=u*m-d*g,I=1/(_*E-v*F+b*M+y*C-B*P+x*w);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*x-g*B+m*y)*I,t[3]=(-c*x+u*B-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*x+g*b-m*v)*I,t[7]=(h*x-u*b+d*v)*I,t[8]=(n*F-a*C+A*w)*I,t[9]=(-i*F+s*C-o*w)*I,t[10]=(p*B-f*b+m*_)*I,t[11]=(-h*B+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,c,u,p,f,g;return h=a*l,c=l*A,u=A*a,p=a*r,f=l*r,g=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*u-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*c+p,i[7]=0,i[8]=n*u+f,i[9]=n*c-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,c=s*l,u=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=c+v,i[2]=u-_,i[3]=0,i[4]=c-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=u+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],c=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-h,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(c,u),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,u),i[1]=0)),i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,c=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=c,t[9]*=c,t[10]*=c,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],c=t[1],u=t[2];if(r===h&&o===c&&n===u)return d.identityMat4();let p,f,g,m,_,v,b,y,B,x;return p=r-h,f=o-c,g=n-u,x=1/Math.sqrt(p*p+f*f+g*g),p*=x,f*=x,g*=x,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,x=Math.sqrt(m*m+_*_+v*v),x?(x=1/x,m*=x,_*=x,v*=x):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,B=p*_-f*m,x=Math.sqrt(b*b+y*y+B*B),x?(x=1/x,b*=x,y*=x,B*=x):(b=0,y=0,B=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=B,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+B*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,h),d.subVec4(r,s,c);const o=2*s[2],n=c[0],a=c[1],l=c[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=h[0]/n,i[9]=h[1]/a,i[10]=-h[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],B=e[13],x=e[14],w=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),c=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"YXZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"ZXY"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"ZYX"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"YZX"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l-A*h*c):"XZY"===t&&(i[0]=A*a*l-n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l+A*h*c),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let c;const u=i+n+h;return u>0?(c=.5/Math.sqrt(u+1),t[3]=.25/c,t[0]=(A-a)*c,t[1]=(r-l)*c,t[2]=(o-s)*c):i>n&&i>h?(c=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/c,t[0]=.25*c,t[1]=(s+o)/c,t[2]=(r+l)/c):n>h?(c=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/c,t[0]=(s+o)/c,t[1]=.25*c,t[2]=(a+A)/c):(c=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/c,t[0]=(r+l)/c,t[1]=(a+A)/c,t[2]=.25*c),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new l(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,c=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+c*-l-u*-a,i[1]=c*A+p*-a+u*-n-h*-l,i[2]=u*A+p*-l+h*-a-c*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,c=l*o,u=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+c,t[2]=f-h,t[4]=p-c,t[5]=1-(u+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],B=e[14],x=e[15];for(s=0;s{const e=new l(3),t=new l(3),i=new l(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],c=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>c?h:c,Math.abs(d.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.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 l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,h=d.MIN_DOUBLE,c=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>c&&(c=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=c,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=c);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;rc&&(c=h);return s[3]=c,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,c=n*a-r*A,u=r*l-o*a,p=Math.sqrt(h*h+c*c+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=c/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,h)=>{h=h||d.vec3();const c=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(c,p);if(f<1e-6)return null;const g=d.subVec3(o,a,s),m=d.dotVec3(g,p);if(m<0||m>f)return null;const _=d.cross3Vec3(g,c,r),v=d.dotVec3(n,_);if(v<0||m+v>f)return null;const b=d.dotVec3(u,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const h=d.subVec3(a,n,t),c=d.subVec3(l,n,i),u=d.cross3Vec3(h,c,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),h=d.subVec3(s,r,i),c=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,h),f=d.dotVec3(A,A),g=d.dotVec3(A,h),m=c*f-u*u;if(0===m)return null;const _=1/m,v=(f*p-u*g)*_,b=(c*g-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,h;const c=new Array(n.length/3);let u,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const h=new Float32Array(a.length);for(let c=0;c>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,c;const u=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),i=new l(4),s=new l(4),r=new l(4),o=new l(4);return(n,a,l,A,h,c)=>{const u=d.mulMat4(l,a,e),p=d.inverseMat4(u,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,d.transformVec4(p,i,s),d.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,d.transformVec4(p,r,o),d.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],d.subVec3(o,s,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l)=>{d.canvasPosToWorldRay(i,s,r,n,e,t),d.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,h;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;An[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{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 m={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 _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:b,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 y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.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 y.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return y.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{x.removeItem(e.id),delete I.scenes[e.id],delete B[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){w.push(e),w.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;w.length>0&&(e<0||s0&&M>0){var t=1e3/M;E+=t,C.push(t),C.length>=30&&(E-=C.shift()),m.frame.fps=Math.round(E/C.length)}for(let e in I.scenes)I.scenes[e].compile();T(e),F=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{D()}),100);const S=function(){let e=Date.now();if(M=e-F,F>0&&M>0){var t=1e3/M;E+=t,C.push(t),C.length>=30&&(E-=C.shift()),m.frame.fps=Math.round(E/C.length)}T(e),function(e){for(var t in P.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];P.sceneId=t,P.startTime=i.startTime,P.deltaTime=null!=P.prevTime?P.time-P.prevTime:0,i.fire("tick",P,!0)}P.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=B[n],s||(s=B[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(S)};function T(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}S();class R{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 R))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+y.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class N{constructor(){this.planes=[new k,new k,new k,new k,new k,new k]}}function Q(e,t,i){const s=d.mulMat4(i,t,O),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],c=s[7],u=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,c-l,g-u,b-m),e.planes[1].set(a+r,c+l,g+u,b+m),e.planes[2].set(a-o,c-A,g-p,b-_),e.planes[3].set(a+o,c+A,g+p,b+_),e.planes[4].set(a-n,c-h,g-f,b-v),e.planes[5].set(a+n,c+h,g+f,b+v)}function H(e,t){let i=N.INSIDE;const s=L,r=U;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class V extends R{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new N,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==V.PICK_MODE_INSIDE&&e!==V.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===V.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=H(this._marqueeFrustum,i.aabb)),s!==N.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,c=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,h*a,c*a,u,1e4,this._marqueeFrustumProjMat),Q(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}V.PICK_MODE_INTERSECTS=0,V.PICK_MODE_INSIDE=1;class j extends R{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const z=d.vec3(),K=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,o),o.slice()}}();function W(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function X(e,t,i,s=1e3){const r=d.getPositionsCenter(e,z),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{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&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Ae.set(this._viewPos),Ae[3]=1,d.transformPoint4(this.scene.camera.projMatrix,Ae,he);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+he[0]/he[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-he[1]/he[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 le?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]),W(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 ue{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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,i=this._wire.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)";var s=this._wireClickable.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)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class de{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&r.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 i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class pe{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 i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-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 fe=d.vec3(),ge=d.vec3();class me extends R{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 i=this.plugin.viewer.scene;this._originMarker=new ce(i,t.origin),this._cornerMarker=new ce(i,t.corner),this._targetMarker=new ce(i,t.target),this._originWorld=d.vec3(),this._cornerWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new ue(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new ue(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new pe(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),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=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>u||f>u||g>u)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);d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,c=t.length;he.offsetTop+(e.offsetParent&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&c(e.offsetParent));this._onMouseHoverSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this.markerDiv.style.left=c(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class be extends G{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new ve(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new me(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{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||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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||"

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());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],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[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 i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}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 i=e[t];this.setField(t,i)}}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 Be=d.vec3(),xe=d.vec3(),we=d.vec3();class Pe extends G{constructor(e,t){super("Annotations",e),this._labelHTML=t.labelHTML||"
",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){var t,i;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){const s=e.pickResult;if(s.worldPos&&s.worldNormal){const e=d.normalizeVec3(s.worldNormal,Be),r=d.mulVec3Scalar(e,this._surfaceOffset,xe);t=d.addVec3(s.worldPos,r,we),i=s.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var s=null;e.markerElementId&&((s=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var r=null;e.labelElementId&&((r=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const o=new ye(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:s,labelElement:r,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:y.apply(e.values,y.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[o.id]=o,o.on("destroyed",(()=>{delete this.annotations[o.id],this.fire("annotationDestroyed",o.id)})),this.fire("annotationCreated",o.id),o}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;t
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Me=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Fe extends R{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Ce(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-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Ie.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Ie.FS_MAX_FLOAT_PRECISION="mediump":Ie.FS_MAX_FLOAT_PRECISION="lowp":Ie.FS_MAX_FLOAT_PRECISION="mediump",Ie.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Ie.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Ie.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Ie.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Ie.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Ie.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Ie.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Ie.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Ie.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Ie.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Ie.SUPPORTED_EXTENSIONS[e]=!0})))}class Se{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Te{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function ke(e){console.error(e.join("\n"))}class Ne{constructor(e,t){this.id=Ue.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 Te(e,e.VERTEX_SHADER,Oe(this.source.vertex)),this._fragmentShader=new Te(e,e.FRAGMENT_SHADER,Oe(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ke(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ke(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ke(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ke(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void ke(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.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 He{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.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-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new He(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new He(this._scene,e.origin),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ne(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,c=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;ze[0]=o,ze[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,c),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,ze),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Ne(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Qe(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Qe(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Qe(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const We=new Float32Array($e(17,[0,1])),Xe=new Float32Array($e(17,[1,0])),Je=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(qe(s,t));return i}(17,4)),Ye=new Float32Array(2);class Ze{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 Ne(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Qe(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Qe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Qe(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),Ye[0]=n,Ye[1]=a,s.uniform2fv(this._uViewport,Ye),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Xe):s.uniform2fv(this._uSampleOffsets,We),s.uniform1fv(this._uSampleWeights,Je);const c=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,c,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function qe(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function $e(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class et{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class tt{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new et(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function it(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const st=function(t,i){i=i||{};const s=new Ee(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},c=!0,u=!0,p=!0,f=!0,g=!0,_=!0,v=!0,b=!0;const y=new tt(t);let B=!1;const x=new Ke(t),w=new Ze(t);function P(){c&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),c=!1,u=!0),u&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),u=!1,p=!0),p&&function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||j>0||k>0||N>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||N>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),N>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||z>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),z>0)for(S=0;S0)for(S=0;S0||W>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||J>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),J>0)for(S=0;S0)for(S=0;S0||Z>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Z>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=u.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let D=null,S=null,T=null,R=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),R=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;S=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),D=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===B&&null==D)return null;let L=null;null!==D&&(L=t.camera.projectWorldPos(D));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===R,h.snappedToVertex="vertex"===R,h.worldPos=D,h.worldNormal=S,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=L||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Ge(t,y),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const ot=new e({});class nt{constructor(e){this.id=ot.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ot.removeItem(this.id)}}class at extends R{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new nt({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class lt extends R{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class At extends R{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ht extends R{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.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(){d.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&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class ct extends R{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new nt({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.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&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ut=d.vec3(),dt=d.vec3(),pt=d.vec3(),ft=d.vec3(),gt=d.vec3(),mt=d.vec3(),_t=d.vec4(),vt=d.vec4(),bt=d.vec4(),yt=d.mat4(),Bt=d.mat4(),xt=d.vec3(),wt=d.vec3(),Pt=d.vec3(),Ct=d.vec3();class Mt extends R{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new nt({deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new lt(this),this._ortho=new At(this),this._frustum=new ht(this),this._customProjection=new ct(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.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?(d.subVec3(this._eye,this._look,xt),d.normalizeVec3(xt,wt),d.mulVec3Scalar(wt,1e3,Pt),d.addVec3(this._look,Pt,Ct),t=Ct):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Bt),d.mulMat4(e.deviceMatrix,Bt,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.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=d.subVec3(this._eye,this._look,ut);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yt),t=d.transformPoint3(yt,t,dt),this.eye=d.addVec3(this._look,t,pt),this.up=d.transformPoint3(yt,this._up,ft)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,ut);const i=d.cross3Vec3(d.normalizeVec3(t,dt),d.normalizeVec3(this._up,pt));d.rotationMat4v(.0174532925*e,i,yt),t=d.transformPoint3(yt,t,ft),this.up=d.transformPoint3(yt,this._up,gt),this.eye=d.addVec3(t,this._look,mt)}yaw(e){let t=d.subVec3(this._look,this._eye,ut);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,yt),t=d.transformPoint3(yt,t,dt),this.look=d.addVec3(t,this._eye,pt),this._gimbalLock&&(this.up=d.transformPoint3(yt,this._up,ft))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,ut);const i=d.cross3Vec3(d.normalizeVec3(t,dt),d.normalizeVec3(this._up,pt));d.rotationMat4v(.0174532925*e,i,yt),this.up=d.transformPoint3(yt,this._up,mt),t=d.transformPoint3(yt,t,ft),this.look=d.addVec3(t,this._eye,gt)}pan(e){const t=d.subVec3(this._eye,this._look,ut),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,dt));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,pt),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,ft),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,gt),this.look=d.addVec3(this._look,i,mt)}zoom(e){const t=d.subVec3(this._eye,this._look,ut),i=Math.abs(d.lenVec3(t,dt)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,pt);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),ft)}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=d.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 d.lenVec3(d.subVec3(this._look,this._eye,ut))}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=_t,i=vt,s=bt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Ft extends R{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Et extends Ft{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new nt({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new et(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class It extends Ft{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Dt extends R{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}var St=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[E.index1],R=i[E.index2],(!L&&T>65535||R>65535)&&(L=!0),y.push(T),y.push(R));return L?new Uint32Array(y):new Uint16Array(y)}}();const Tt=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/h,l/h,A/h],t),d.mulMat4(e,t,s),s}}();var Rt=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Ot(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function kt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Nt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Ut(e,a,"floor","ceil"),s=Ot(i),o=kt(e,a,s),o>n&&(r=i,n=o),i=Ut(e,a,"ceil","ceil"),s=Ot(i),o=kt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Qt=m.memory,Ht=d.AABB3();class Vt extends Dt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new nt({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Nt.getPositionsBounds(t.positions),s=Nt.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Nt.getUVBounds(t.uv),s=Nt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Nt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Qt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Qt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Qt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new Qe(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Qt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Qt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Qe(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Qt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=St(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Qt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Qt.positions+=this._pickTrianglePositionsBuf.numItems,Qt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Nt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Nt.getPositionsBounds(e),s=Nt.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Nt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Nt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,Ht,this._state.positionsDecodeMatrix),d.AABB3ToOBB3(Ht,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Qt.meshes--}}function jt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Gt extends R{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const zt={opaque:0,mask:1,blend:2},Kt=["opaque","mask","blend"];class Wt extends Gt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new nt({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=zt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Kt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Xt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Jt extends Gt{get type(){return"EmphasisMaterial"}get presets(){return Xt}constructor(e,t={}){super(e,t),this._state=new nt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Xt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Xt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Zt extends Gt{get type(){return"EdgeMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new nt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const qt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class $t extends R{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return qt}set units(e){e||(e="meters");qt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class ei extends R{constructor(e,t={}){super(e,t),this._supported=Ie.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const ti={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class ii extends Gt{get type(){return"PointsMaterial"}get presets(){return ti}constructor(e,t={}){super(e,t),this._state=new nt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=ti[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ti).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const si={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ri extends Gt{get type(){return"LinesMaterial"}get presets(){return si}constructor(e,t={}){super(e,t),this._state=new nt({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=si[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(si).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function oi(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new st(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+y.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],y.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=oi(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=oi(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ai=1e3,li=1001,Ai=1002,hi=1003,ci=1004,ui=1004,di=1005,pi=1005,fi=1006,gi=1007,mi=1007,_i=1008,vi=1008,bi=1009,yi=1010,Bi=1011,xi=1012,wi=1013,Pi=1014,Ci=1015,Mi=1016,Fi=1017,Ei=1018,Ii=1020,Di=1021,Si=1022,Ti=1023,Ri=1024,Li=1025,Ui=1026,Oi=1027,ki=1028,Ni=1029,Qi=1030,Hi=1031,Vi=1033,ji=33776,Gi=33777,zi=33778,Ki=33779,Wi=35840,Xi=35841,Ji=35842,Yi=35843,Zi=36196,qi=37492,$i=37496,es=37808,ts=37809,is=37810,ss=37811,rs=37812,os=37813,ns=37814,as=37815,ls=37816,As=37817,hs=37818,cs=37819,us=37820,ds=37821,ps=36492,fs=3e3,gs=3001,ms=1e4,_s=10001,vs=10002,bs=10003,ys=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=ws(e),u=s.getNumAllocatedSectionPlanes()>0,d=xs(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=ws(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=xs(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Bs[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Bs[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Bs[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Bs[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Bs[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Bs[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Es{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Is=new e({}),Ds=d.vec3(),Ss=function(e,t){this.id=Is.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Es(t),this._allocate(t)},Ts={};Ss.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ts[t];return i||(i=new Ss(t,e),Ts[t]=i,m.memory.programs++),i._useCount++,i},Ss.prototype.put=function(){0==--this._useCount&&(Is.removeItem(this.id),this._program&&this._program.destroy(),delete Ts[this._hash],m.memory.programs--)},Ss.prototype.webglContextRestored=function(){this._program=null},Ss.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ls=new e({}),Us=d.vec3(),Os=function(e,t){this.id=Ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Rs(t),this._allocate(t)},ks={};Os.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ks[t];return i||(i=new Os(t,e),ks[t]=i,m.memory.programs++),i._useCount++,i},Os.prototype.put=function(){0==--this._useCount&&(Ls.removeItem(this.id),this._program&&this._program.destroy(),delete ks[this._hash],m.memory.programs--)},Os.prototype.webglContextRestored=function(){this._program=null},Os.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Qs=d.vec3(),Hs=function(e,t){this._hash=e,this._shaderSource=new Ns(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Vs={};Hs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Vs[t];if(!i){if(i=new Hs(t,e),i.errors)return console.log(i.errors.join("\n")),null;Vs[t]=i,m.memory.programs++}return i._useCount++,i},Hs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Vs[this._hash],m.memory.programs--)},Hs.prototype.webglContextRestored=function(){this._program=null},Hs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Hs.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ne(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Gs=d.vec3(),zs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new js(t),this._allocate(t)},Ks={};zs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ks[t];if(!i){if(i=new zs(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ks[t]=i,m.memory.programs++}return i._useCount++,i},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ks[this._hash],m.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Xs=d.vec3(),Js=function(e,t){this._hash=e,this._shaderSource=new Ws(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ys={};Js.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Ys[t];if(!i){if(i=new Js(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ys[t]=i,m.memory.programs++}return i._useCount++,i},Js.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ys[this._hash],m.memory.programs--)},Js.prototype.webglContextRestored=function(){this._program=null},Js.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const qs=function(e,t){this._hash=e,this._shaderSource=new Zs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},$s={};qs.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=$s[i];if(!s){if(s=new qs(i,e),s.errors)return console.log(s.errors.join("\n")),null;$s[i]=s,m.memory.programs++}return s._useCount++,s},qs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete $s[this._hash],m.memory.programs--)},qs.prototype.webglContextRestored=function(){this._program=null},qs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},qs.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Ne(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ur=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),B=d.vec3(),x=d.vec3(),w=d.vec3(),P=d.vec3(),C=d.vec3(),M=d.vec3(),F=d.vec3(),E=d.vec3(),I=d.vec3();return function(D,S,T,R){var L=R.primIndex;if(null!=L&&L>-1){const N=D.geometry._state,Q=D.scene,H=Q.camera,V=Q.canvas;if("triangles"===N.primitiveName){R.primitive="triangle";const Q=L,j=N.indices,G=N.positions;let z,W,X;if(j){var U=j[Q+0],O=j[Q+1],k=j[Q+2];o[0]=U,o[1]=O,o[2]=k,R.indices=o,z=3*U,W=3*O,X=3*k}else z=3*Q,W=z+3,X=W+3;if(i[0]=G[z+0],i[1]=G[z+1],i[2]=G[z+2],s[0]=G[W+0],s[1]=G[W+1],s[2]=G[W+2],r[0]=G[X+0],r[1]=G[X+1],r[2]=G[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(Nt.decompressPosition(i,e,i),Nt.decompressPosition(s,e,s),Nt.decompressPosition(r,e,r))}R.canvasPos?d.canvasPosToLocalRay(V.canvas,D.origin?K(S,D.origin):S,T,D.worldMatrix,R.canvasPos,e,t):R.origin&&R.direction&&d.worldRayToLocalRay(D.worldMatrix,R.origin,R.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),R.localPos=n,R.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,d.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],R.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),R.worldPos=a,d.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],R.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),R.bary=A;const J=N.normals;if(J){if(N.compressGeometry){const e=3*U,t=3*O,i=3*k;Nt.decompressNormal(J.subarray(e,e+2),h),Nt.decompressNormal(J.subarray(t,t+2),c),Nt.decompressNormal(J.subarray(i,i+2),u)}else h[0]=J[z],h[1]=J[z+1],h[2]=J[z+2],c[0]=J[W],c[1]=J[W+1],c[2]=J[W+2],u[0]=J[X],u[1]=J[X+1],u[2]=J[X+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(h,A[0],b),d.mulVec3Scalar(c,A[1],y),B),d.mulVec3Scalar(u,A[2],x),w);R.worldNormal=d.normalizeVec3(d.transformVec3(D.worldNormalMatrix,e,P))}const Y=N.uv;if(Y){if(p[0]=Y[2*U],p[1]=Y[2*U+1],f[0]=Y[2*O],f[1]=Y[2*O+1],g[0]=Y[2*k],g[1]=Y[2*k+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(Nt.decompressUV(p,e,p),Nt.decompressUV(f,e,f),Nt.decompressUV(g,e,g))}R.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),F),d.mulVec2Scalar(g,A[2],E),I)}}}}}();function dr(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],_=[],v=[];let b,B,x,w,P,C,M,F,E,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(P=t-b*f,C=c-b*u,B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),m.push(P*x),m.push(S),m.push(P*w),_.push(B*p),_.push(1*b/o),g.push(P*x+l),g.push(C+A),g.push(P*w+h);for(b=0;b0){for(E=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(t*x),m.push(1),m.push(t*w),_.push(I),_.push(D),g.push(t*x+l),g.push(c+A),g.push(t*w+h);for(B=0;B0){for(E=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),B=0;B<=r;B++)x=Math.sin(B*d),w=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(i*x),m.push(-1),m.push(i*w),_.push(I),_.push(D),g.push(i*x+l),g.push(0-c+A),g.push(i*w+h);for(B=0;B":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function gr(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,_=(l||"").split("\n"),v=0,b=0,B=.04,x=0;x<_.length;x++){A=0,c=(h=_[x]).length;for(var w=0;w0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=Ur(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=Ur(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=Ur(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Qr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Qr(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Ur(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Ur(i,this.magFilter)));const a=Ur(i,this.format,this.encoding),l=Ur(i,this.type),A=Nr(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Gr extends R{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new nt({texture:new kr({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new kr({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Hr(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=Hr(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}class zr extends R{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new nt({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const Kr=m.memory,Wr=d.AABB3();class Xr extends Dt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new nt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Nt.getPositionsBounds(t.positions),o=Nt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new Qe(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Kr.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,Wr,i.positionsDecodeMatrix),d.AABB3ToOBB3(Wr,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new Qe(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Kr.colors+=i.colorsBuf.numItems}if(t.uv){const e=Nt.getUVBounds(t.uv),r=Nt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new Qe(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Kr.uvs+=i.uvBuf.numItems}if(t.normals){const e=Nt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new Qe(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Kr.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Kr.indices+=i.indicesBuf.numItems;const o=St(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Kr.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Kr.meshes--}}var Jr={};function Yr(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=Jr.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function Zr(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=Jr.parse.fromOBJ(e),n=Jr.edit.unwrap(o.i_verts,o.c_verts,3),a=Jr.edit.unwrap(o.i_norms,o.c_norms,3),l=Jr.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function qr(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function $r(e={}){return qr({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function eo(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}function to(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,B,x,w,P,C,M,F=0,E=0;for(b=0;b65535?Uint32Array:Uint16Array)(c*u*6);for(b=0;b360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],c=[],u=[],p=[];let f,g,m,_,v,b,B,x,w,P,C,M;for(x=0;x<=r;x++)for(B=0;B<=s;B++)f=B/s*o,g=.785398+x/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),_=(t+i*Math.cos(g))*Math.sin(f),v=i*Math.sin(g),h.push(m+a),h.push(_+l),h.push(v+A),u.push(1-B/s),u.push(x/r),b=d.normalizeVec3(d.subVec3([m,_,v],[a,l,A],[]),[]),c.push(b[0]),c.push(b[1]),c.push(b[2]);for(x=1;x<=r;x++)for(B=1;B<=s;B++)w=(s+1)*x+B-1,P=(s+1)*(x-1)+B-1,C=(s+1)*(x-1)+B,M=(s+1)*x+B,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return y.apply(e,{positions:h,normals:c,uv:u,indices:p})}function so(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e[...e])).flat();return so({id:e.id,points:t})}Jr.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},Jr.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(Jr.parse._buffToStr(e));window.location.href=i},Jr.clone=function(e){return JSON.parse(JSON.stringify(e))},Jr.bin={},Jr.bin.f=new Float32Array(1),Jr.bin.fb=new Uint8Array(Jr.bin.f.buffer),Jr.bin.rf=function(e,t){for(var i=Jr.bin.f,s=Jr.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Jr.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Jr.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Jr.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Jr.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Jr.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Jr.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Jr.parse={},Jr.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class oo extends R{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new Gr(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Fr(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new cr(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Vt(this,to({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Wt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const no=d.OBB3(),ao=d.OBB3(),lo=d.OBB3();class Ao{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(d.AABB3ToOBB3(this._aabbLocal,no),this.transform?(d.transformOBB3(this.transform.worldMatrix,no,ao),d.transformOBB3(this.model.worldMatrix,ao,lo),d.OBB3ToAABB3(lo,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,no,ao),d.OBB3ToAABB3(ao,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const ho=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let co=0;const uo={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},po=new Float32Array([1,1,1,1]),fo=new Float32Array([0,0,0,1]),go=d.vec4(),mo=d.vec3(),_o=d.vec3(),vo=d.mat4();class bo{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;go[0]=i,go[1]=s,go[2]=t.blendCutoff,go[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,go),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===uo[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===uo[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===uo[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?fo:po)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,m.memory.programs--}}class yo extends bo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Bo extends yo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class xo extends yo{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = vColor;"),o.push("}"),o}}class Po extends yo{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class Co extends Po{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Mo extends Po{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Fo extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Eo extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Io extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Do extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class So extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class To extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Ro extends yo{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class Lo extends yo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Oo extends yo{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.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 );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Go=d.vec3(),zo=d.vec3(),Ko=d.vec3(),Wo=d.vec3(),Xo=d.mat4();class Jo extends bo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Go;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=zo;if(l){const e=Ko;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Xo),m=Wo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Yo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new wo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Fo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Eo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new jo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Jo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Bo(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Bo(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new xo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new xo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Oo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Oo(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Lo(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Lo(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new wo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new So(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new To(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Co(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Mo(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fo(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Io(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Uo(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Eo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Do(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ro(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Jo(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new jo(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Zo={};let qo=65536,$o=5e6;class en{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),qo=e}get maxDataTextureHeight(){return qo}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),$o=e}get maxGeometryBatchSize(){return $o}}const tn=new en;class sn{constructor(){this.maxVerts=tn.maxGeometryBatchSize,this.maxIndices=3*tn.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const rn=d.mat4(),on=d.mat4();function nn(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,c=65525,u=c/l,p=c/A,f=c/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function An(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const hn=d.mat4(),cn=d.mat4(),un=d.vec4([0,0,0,1]),dn=d.vec3(),pn=d.vec3(),fn=d.vec3(),gn=d.vec3(),mn=d.vec3(),_n=d.vec3(),vn=d.vec3();class bn{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Zo[t];return i||(i=new Yo(e),Zo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Zo[t],i._destroy()}))),i}(e.model.scene),this._buffer=new sn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new nt({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=hn;m?d.inverseMat4(d.transposeMat4(m,cn),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,c,u=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;ch&&(l=n,h=A),n=ln(p,"floor","ceil"),a=An(n),A=o(p,a),A>h&&(l=n,h=A),n=ln(p,"ceil","ceil"),a=An(n),A=o(p,a),A>h&&(l=n,h=A),s[r+c+0]=l[0],s[r+c+1]=l[1],s[r+c+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):nn(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new Qe(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Nt.getUVBounds(i.uv),r=Nt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new Qe(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Qe(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class yn extends bo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Bn extends yn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}class xn extends yn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Pn extends yn{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Cn extends Pn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Mn extends Pn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Fn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class En extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class In extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Dn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Sn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class Tn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Rn extends yn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ln={3e3:"linearToLinear",3001:"sRGBToLinear"};class Un extends yn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Ln[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Ln[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class kn extends yn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const zn=d.vec3(),Kn=d.vec3(),Wn=d.vec3(),Xn=d.vec3(),Jn=d.mat4();class Yn extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=zn;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Kn;if(l){const e=d.transformPoint3(h,l,Wn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Jn),m=Xn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Zn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new wn(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Fn(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new En(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Gn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Yn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Bn(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Bn(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new xn(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new xn(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Un(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Un(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new kn(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new kn(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new wn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Sn(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Tn(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Cn(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Mn(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fn(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new In(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new On(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new En(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Dn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Rn(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Gn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Yn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const qn={};const $n=new Uint8Array(4),ea=new Float32Array(1),ta=d.vec4([0,0,0,1]),ia=new Float32Array(3),sa=d.vec3(),ra=d.vec3(),oa=d.vec3(),na=d.vec3(),aa=d.vec3(),la=d.vec3(),Aa=d.vec3(),ha=new Float32Array(4);class ca{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=qn[t];return i||(i=new Zn(e),qn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete qn[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new nt({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Qe(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Qe(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new Qe(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Qe(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Qe(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Qe(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Qe(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Qe(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";$n[0]=t[0],$n[1]=t[1],$n[2]=t[2],$n[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData($n,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Z),r=!!(t&ie),o=!!(t&se),n=!!(t&re),a=!!(t&oe),l=!!(t&$),A=!!(t&q);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?uo.NOT_RENDERED:i?uo.COLOR_TRANSPARENT:uo.COLOR_OPAQUE,c=!s||A?uo.NOT_RENDERED:n?uo.SILHOUETTE_SELECTED:o?uo.SILHOUETTE_HIGHLIGHTED:r?uo.SILHOUETTE_XRAYED:uo.NOT_RENDERED;let u=0;u=!s||A?uo.NOT_RENDERED:n?uo.EDGES_SELECTED:o?uo.EDGES_HIGHLIGHTED:r?uo.EDGES_XRAYED:a?i?uo.EDGES_COLOR_TRANSPARENT:uo.EDGES_COLOR_OPAQUE:uo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?uo.PICK:uo.NOT_RENDERED)<<12,d|=(t&ee?1:0)<<16,ea[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(ea,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ia[0]=t[0],ia[1]=t[1],ia[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(ia,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],c=ta,u=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&d.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ua extends bo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class da extends ua{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class pa extends ua{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const fa=d.vec3(),ga=d.vec3(),ma=d.vec3(),_a=d.vec3(),va=d.mat4();class ba extends bo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=fa;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ga;if(l){const e=ma;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,va),m=_a,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ya=d.vec3(),Ba=d.vec3(),xa=d.vec3(),wa=d.vec3(),Pa=d.mat4();class Ca extends bo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ya;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ba;if(l){const e=xa;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Pa),m=wa,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ma{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new da(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pa(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ba(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ca(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Fa={};class Ea{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class Ia{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Fa[t];return i||(i=new Ma(e),Fa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Fa[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Ea(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new nt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=nn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Qe(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class Ta extends Da{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Ra=d.vec3(),La=d.vec3(),Ua=d.vec3();d.vec3();const Oa=d.mat4();class ka extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ra;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=La;if(l){const e=d.transformPoint3(h,l,Ua);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Oa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Na=d.vec3(),Qa=d.vec3(),Ha=d.vec3();d.vec3();const Va=d.mat4();class ja extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Na;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Qa;if(l){const e=d.transformPoint3(h,l,Ha);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Va),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ga{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new ka(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ja(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Sa(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ta(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ka(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ja(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const za={};const Ka=new Uint8Array(4),Wa=new Float32Array(1),Xa=new Float32Array(3),Ja=new Float32Array(4);class Ya{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=za[t];return i||(i=new Ga(e),za[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete za[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new nt({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Qe(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new Qe(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new Qe(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Qe(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ka[0]=t[0],Ka[1]=t[1],Ka[2]=t[2],Ka[3]=t[3],this._state.colorsBuf.setData(Ka,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Z),r=!!(t&ie),o=!!(t&se),n=!!(t&re),a=!!(t&oe),l=!!(t&$),A=!!(t&q);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?uo.NOT_RENDERED:i?uo.COLOR_TRANSPARENT:uo.COLOR_OPAQUE,c=!s||A?uo.NOT_RENDERED:n?uo.SILHOUETTE_SELECTED:o?uo.SILHOUETTE_HIGHLIGHTED:r?uo.SILHOUETTE_XRAYED:uo.NOT_RENDERED;let u=0;u=!s||A?uo.NOT_RENDERED:n?uo.EDGES_SELECTED:o?uo.EDGES_HIGHLIGHTED:r?uo.EDGES_XRAYED:a?i?uo.EDGES_COLOR_TRANSPARENT:uo.EDGES_COLOR_OPAQUE:uo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?uo.PICK:uo.NOT_RENDERED)<<12,d|=(t&ee?255:0)<<16,Wa[0]=d,this._state.flagsBuf.setData(Wa,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Xa[0]=t[0],Xa[1]=t[1],Xa[2]=t[2],this._state.offsetsBuf.setData(Xa,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Ja[0]=t[0],Ja[1]=t[4],Ja[2]=t[8],Ja[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ja,i),Ja[0]=t[1],Ja[1]=t[5],Ja[2]=t[9],Ja[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ja,i),Ja[0]=t[2],Ja[1]=t[6],Ja[2]=t[10],Ja[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ja,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,uo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,uo.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Za extends bo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class qa extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class $a extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class el extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class tl extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class il extends Za{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const sl=d.vec3(),rl=d.vec3(),ol=d.vec3(),nl=d.vec3(),al=d.mat4();class ll extends bo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=sl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=rl;if(l){const e=ol;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,al),m=nl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Al=d.vec3(),hl=d.vec3(),cl=d.vec3(),ul=d.vec3(),dl=d.mat4();class pl extends bo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Al;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=hl;if(l){const e=cl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,dl),m=ul,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class fl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new qa(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new $a(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new el(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new tl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new il(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ll(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new pl(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const gl={};class ml{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class _l{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=gl[t];return i||(i=new fl(e),gl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete gl[t],i._destroy()}))),i}(e.model.scene),this._buffer=new ml(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new nt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=nn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new Qe(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Qe(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class yl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Bl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class xl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class wl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Pl extends vl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class Cl extends vl{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ml=d.vec3(),Fl=d.vec3(),El=d.vec3();d.vec3();const Il=d.mat4();class Dl extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ml;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Fl;if(l){const e=d.transformPoint3(h,l,El);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Il),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Sl=d.vec3(),Tl=d.vec3(),Rl=d.vec3();d.vec3();const Ll=d.mat4();class Ul extends bo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Sl;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Tl;if(l){const e=d.transformPoint3(h,l,Rl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Ll),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ol{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new bl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new yl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Pl(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Bl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new xl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new wl(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Cl(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Dl(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ul(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const kl={};const Nl=new Uint8Array(4),Ql=new Float32Array(1),Hl=new Float32Array(3),Vl=new Float32Array(4);class jl{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=kl[t];return i||(i=new Ol(e),kl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete kl[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new nt({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new Qe(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new Qe(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new Qe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new Qe(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Nl[0]=t[0],Nl[1]=t[1],Nl[2]=t[2],this._state.colorsBuf.setData(Nl,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Z),r=!!(t&ie),o=!!(t&se),n=!!(t&re),a=!!(t&oe),l=!!(t&$),A=!!(t&q);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?uo.NOT_RENDERED:i?uo.COLOR_TRANSPARENT:uo.COLOR_OPAQUE,c=!s||A?uo.NOT_RENDERED:n?uo.SILHOUETTE_SELECTED:o?uo.SILHOUETTE_HIGHLIGHTED:r?uo.SILHOUETTE_XRAYED:uo.NOT_RENDERED;let u=0;u=!s||A?uo.NOT_RENDERED:n?uo.EDGES_SELECTED:o?uo.EDGES_HIGHLIGHTED:r?uo.EDGES_XRAYED:a?i?uo.EDGES_COLOR_TRANSPARENT:uo.EDGES_COLOR_OPAQUE:uo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?uo.PICK:uo.NOT_RENDERED)<<12,d|=(t&ee?255:0)<<16,Ql[0]=d,this._state.flagsBuf.setData(Ql,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Hl[0]=t[0],Hl[1]=t[1],Hl[2]=t[2],this._state.offsetsBuf.setData(Hl,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Vl[0]=t[0],Vl[1]=t[4],Vl[2]=t[8],Vl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Vl,i),Vl[0]=t[1],Vl[1]=t[5],Vl[2]=t[9],Vl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Vl,i),Vl[0]=t[2],Vl[1]=t[6],Vl[2]=t[10],Vl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Vl,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,uo.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,uo.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,uo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,uo.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Gl=d.vec3(),zl=d.vec3(),Kl=d.mat4();class Wl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Gl;if(g){const t=d.transformPoint3(c,A,zl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,Kl)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Xl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wl(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Jl={};class Yl{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Zl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class ql{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const $l={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify($l,null,4));let e=0;Object.keys($l).forEach((t=>{t.startsWith("size")&&(e+=$l[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/$l.totalLines).toFixed(2)}`);let t={};Object.keys($l).forEach((i=>{i.startsWith("size")&&(t[i]=`${($l[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class eA{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);$l.sizeDataColorsAndFlags+=l.byteLength,$l.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);$l.sizeDataTextureOffsets+=r.byteLength,$l.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);$l.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Yl,this._dataTextureState=new Zl,this._dataTextureGenerator=new eA,this._state=new nt({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&$l.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*iA||t+r>4096*iA)&&$l.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*iA&&t+r<=4096*iA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;$l.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,$l.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||aA),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,$l.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,$l.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,$l.totalLines32Bits+=t.numLines),$l.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,rA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,rA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,rA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,oA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,sA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const AA=d.vec3(),hA=d.vec3(),cA=d.vec3();d.vec3();const uA=d.vec4(),dA=d.mat4();class pA{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=AA;if(g){const t=d.transformPoint3(c,A,hA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,dA),f=cA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const fA=new Float32Array([1,1,1]),gA=d.vec3(),mA=d.vec3(),_A=d.vec3();d.vec3();const vA=d.mat4();class bA{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=gA;if(A){const t=mA;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,vA),g=_A,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===uo.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,fA);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const yA=new Float32Array([0,0,0,1]),BA=d.vec3(),xA=d.vec3();d.vec3();const wA=d.mat4();class PA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=BA;if(g){const t=d.transformPoint3(c,A,xA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,wA)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===uo.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===uo.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,yA);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 CA=d.vec3(),MA=d.vec3(),FA=d.mat4();class EA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=CA;if(g){const t=d.transformPoint3(c,A,MA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,FA)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 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 IA=d.vec3(),DA=d.vec3(),SA=d.vec3(),TA=d.mat4();class RA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=IA;if(g){const t=d.transformPoint3(c,A,DA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(o.viewMatrix,e,TA),f=SA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const LA=d.vec3(),UA=d.vec3(),OA=d.vec3();d.vec3();const kA=d.mat4();class NA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=LA;if(A){const e=UA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=K(p,t,kA),g=OA,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 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 QA=d.vec3(),HA=d.vec3(),VA=d.vec3(),jA=d.vec3();d.vec3();const GA=d.mat4();class zA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=QA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=HA;if(v){const e=d.transformPoint3(c,A,VA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,GA),_=jA,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(x,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(x,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(x,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const KA=d.vec3(),WA=d.vec3(),XA=d.vec3(),JA=d.vec3();d.vec3();const YA=d.mat4();class ZA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=KA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=WA;if(v){const e=XA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,YA),_=JA,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qA=d.vec3(),$A=d.vec3(),eh=d.vec3();d.vec3();const th=d.mat4();class ih{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=qA;if(A){const t=$A;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,th),g=eh,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const sh=d.vec3(),rh=d.vec3(),oh=d.vec3();d.vec3();const nh=d.mat4();class ah{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=sh;if(g){const t=d.transformPoint3(c,A,rh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,nh),f=oh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const lh=d.vec3(),Ah=d.vec3(),hh=d.vec3();d.vec3();const ch=d.mat4();class uh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=lh;if(g){const t=Ah;d.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=K(u,e,ch),f=hh,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Ie.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&&Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Ie.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dh=d.vec3(),ph=d.vec3(),fh=d.vec3();d.vec3(),d.vec4();const gh=d.mat4();class mh{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=dh;if(g){const t=d.transformPoint3(c,A,ph);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,gh),f=fh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Ne(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class _h{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new bA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new RA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new NA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new mh(this._scene)),this._snapRenderer||(this._snapRenderer=new zA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new ZA(this._scene)),this._snapRenderer||(this._snapRenderer=new zA(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new pA(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new pA(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new bA(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ah(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new uh(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new PA(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new EA(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new RA(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new mh(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new mh(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new NA(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new zA(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ZA(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ih(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const vh={};class bh{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class yh{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Bh={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Bh,null,4));let e=0;Object.keys(Bh).forEach((t=>{t.startsWith("size")&&(e+=Bh[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Bh.totalPolygons).toFixed(2)}`);let t={};Object.keys(Bh).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Bh[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class xh{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Bh.sizeDataColorsAndFlags+=h.byteLength,Bh.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Bh.sizeDataTextureOffsets+=r.byteLength,Bh.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new ql(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Bh.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete vh[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new bh,this._dtxState=new yh,this._dtxTextureFactory=new xh,this._state=new nt({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Bh.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*Ph||t+r>4096*Ph)&&Bh.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Ph&&t+r<=4096*Ph}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Bh.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Bh.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Bh.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||Ih),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Bh.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Bh.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Bh.totalPolygons32Bits+=t.numTriangles),Bh.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Bh.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Bh.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Bh.totalEdges32Bits+=t.numEdges),Bh.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&Z&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&se&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ie&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&re&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&ee&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&oe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&$&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&q&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Z?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&ie?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&ee?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Mh)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,Mh))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Mh))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Fh))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ch))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,uo.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,uo.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,uo.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,uo.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,uo.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,uo.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,uo.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,uo.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,uo.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,uo.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,uo.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,uo.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,uo.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,uo.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class Sh{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class Th{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Rh={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Lh{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==kh[e])return void kh[e].push({onLoad:t,onProgress:i,onError:s});kh[e]=[],kh[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=kh[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{Rh.add(e,t);const i=kh[e];delete kh[e];for(let e=0,s=i.length;e{const i=kh[e];if(void 0===i)throw this.manager.itemError(e),t;delete kh[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Qh{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Hh=0;class Vh{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Qh,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Nh;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new Nh;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=Vh.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(Vh.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Vh.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Vh.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),Hh>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Hh++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Hh--}}Vh.BasisFormat={ETC1S:0,UASTC_4x4:1},Vh.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},Vh.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},Vh.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete jh[t],i.destroy()}))),i} /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT @@ -14,7 +14,7 @@ class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){ /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT - **/let Jh=null;function Yh(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const h=Math.min(r=Jh[i],o=Jh[i+1],n=Jh[i+2]),c=Math.min(a=Jh[s],l=Jh[s+1],A=Jh[s+2]);if(h!==c)return h-c;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let Zh=null;function qh(e,t){let i=Zh[2*e]-Zh[2*t];return 0!==i?i:Zh[2*e+1]-Zh[2*t+1]}function $h(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e>t;i.sort(Yh);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}Zh=new Int32Array(e),t.sort(qh);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new Th({id:"defaultColorTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Th({id:"defaultMetalRoughTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new Th({id:"defaultNormalsTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new Th({id:"defaultEmissiveTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new Th({id:"defaultOcclusionTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Sh({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||pc),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new Th({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new Sh({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(this.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new ac({id:e.id,model:this,parentTransform:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||hc,i=e.position||cc,s=e.rotation||uc;d.eulerToQuaternion(s,"XYZ",dc),e.meshMatrix=d.composeMat4(i,dc,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=an(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):fc,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];X(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=nn(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Nt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new ca({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new ca({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Ya({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new jl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=Z),this._pickable&&!1!==e.pickable&&(t|=$),this._culled&&!1!==e.culled&&(t|=q),this._clippable&&!1!==e.clippable&&(t|=ee),this._collidable&&!1!==e.collidable&&(t|=te),this._edges&&!1!==e.edges&&(t|=oe),this._xrayed&&!1!==e.xrayed&&(t|=ie),this._highlighted&&!1!==e.highlighted&&(t|=se),this._selected&&!1!==e.selected&&(t|=re),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class _c extends R{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ep.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,B=v.filter((e=>!b[e])),x=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=Pc(e.location,vc),i=Pc(e.direction,vc);A&&d.negateVec3(i),d.subVec3(t,l),r.yUp&&(t=Mc(t),i=Mc(i)),new _r(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new _c(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=Pc(e.location,bc),n=Pc(e.normal,yc),a=Pc(e.up,Bc),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=Mc(o),n=Mc(n),a=Mc(a)),new oo(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,c;if(e.perspective_camera?(a=Pc(e.perspective_camera.camera_view_point,vc),A=Pc(e.perspective_camera.camera_direction,vc),h=Pc(e.perspective_camera.camera_up_vector,vc),r.perspective.fov=e.perspective_camera.field_of_view,c="perspective"):(a=Pc(e.orthogonal_camera.camera_view_point,vc),A=Pc(e.orthogonal_camera.camera_direction,vc),h=Pc(e.orthogonal_camera.camera_up_vector,vc),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,c="ortho"),d.subVec3(a,l),r.yUp&&(a=Mc(a),A=Mc(A),h=Mc(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:d.addVec3(a,A,vc)}else A=d.addVec3(a,A,vc);n?(r.eye=a,r.look=A,r.up=h,r.projection=c):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:c})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=d.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}}function wc(e){return{x:e[0],y:e[1],z:e[2]}}function Pc(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Cc(e){return new Float64Array([e[0],-e[2],e[1]])}function Mc(e){return new Float64Array([e[0],e[2],-e[1]])}const Fc=d.vec3(),Ec=(e,t,i,s)=>{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class Ic extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ce(i,t.origin),this._targetMarker=new ce(i,t.target),this._originWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ue(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ue(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ue(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ue(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new pe(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new pe(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new pe(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new pe(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],c=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var u=0,p=s.length;u{const t=e.snappedCanvasPos||e.canvasPos;if(r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState){const i=s.getBoundingClientRect(),r=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,n=i.left+r,a=i.top+o;this._markerDiv.style.left=n+t[0]-5+"px",this._markerDiv.style.top=a+t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity}else this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px";s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class Tc extends G{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Sc(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new Ic(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,s=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{s&&(i-=t.deltaTime,(!this._delayBeforeRestore||i<=0)&&(e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class Lc{constructor(){}getMetaModel(e,t,i){y.loadJSON(e,(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){y.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){y.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Uc{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=Oc(e,i);return s?t?kc(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=Oc(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=kc(r,[t]),i&&(r=kc(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function Oc(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class Qc extends Nc{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const Hc=d.vec3();class Vc extends R{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Qc(this),this._lookCurve=new Qc(this),this._upCurve=new Qc(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Hc),t.look=this._lookCurve.getPoint(e,Hc),t.up=this._upCurve.getPoint(e,Hc)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e=1;e>1&&(e=1);const i=this.easing?Xc._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,Wc),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,zc),s.look=d.subVec3(zc,Wc,Gc)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Gc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Kc)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,zc),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Gc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Kc)),this._projection2){const t="ortho"===this._projection2?Xc._easeOutExpo(e,0,1,1):Xc._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Jc extends R{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Xc(this),this._t=0,this.state=Jc.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case Jc.SCRUBBING:return;case Jc.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Jc.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Jc.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=Jc.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Jc.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Jc.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=Jc.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Jc.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Jc.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Jc.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Jc.STOPPED=0,Jc.SCRUBBING=1,Jc.PLAYING=2,Jc.PLAYING_TO=3;const Yc=d.vec3(),Zc=d.vec3();d.vec3();const qc=d.vec3([0,-1,0]),$c=d.vec4([0,0,0,1]);class eu extends R{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new Gr(this),this._plane=new cr(this,{geometry:new Vt(this,to({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Wt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new cr(this,{geometry:new Vt(this,eo({size:1,divisions:10})),material:new Wt(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Fr(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),W(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,Yc);const s=-d.dotVec3(i,Yc);d.normalizeVec3(i),d.mulVec3Scalar(i,s,Zc),d.vec3PairToQuaternion(qc,e,$c),this._node.quaternion=$c}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class tu extends Ft{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new nt({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new et(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function iu(e){if(!su(e.width)||!su(e.height)){const t=document.createElement("canvas");t.width=ru(e.width),t.height=ru(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function su(e){return 0==(e&e-1)}function ru(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class ou extends R{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new nt({texture:new kr({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class Au{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const hu=d.vec3();class cu{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!i||i.pickable,h=!i||i.colorize,c=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class fu extends Nc{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class mu extends gc{constructor(e,t={}){super(e,t)}}class _u extends R{constructor(e,t={}){super(e,t),this._skyboxMesh=new cr(this,{geometry:new Vt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Wt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Gr(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class vu{transcode(e,t,i={}){}destroy(){}}const bu=d.vec4(),yu=d.vec4(),Bu=d.vec3(),xu=d.vec3(),wu=d.vec3(),Pu=d.vec4(),Cu=d.vec4(),Mu=d.vec4();class Fu{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,Bu);s=d.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),W(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Xr(this._scene,pr({radius:s})),this._pivotSphere=new cr(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(W(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Wt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,Eu)),i=d.cross3Vec3(t,e.worldUp,Iu);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=Su;t.project.unproject(e,a,Tu,Ru,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,Eu)),h=d.addVec3(t.eye,d.mulVec3Scalar(A,i,Iu),Du);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=d.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),a=this.getPivotPos();d.addVec3(o,a);let l=d.lookAtMat4v(o,a,i.worldUp);l=d.inverseMat4(l);const A=d.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],d.subVec3(i.eye,d.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Uu{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Se;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Ou=d.vec2();class ku{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,c=0,u=0,p=!1;const f=d.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],c=t[3],u=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l){const t=u-A,i=g-h,s=e.camera;if("perspective"===s.projection){const o=Math.abs(p?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/c,r.panDeltaY+=1.5*i*o/c}else r.panDeltaX+=.5*s.ortho.scale*(t/c),r.panDeltaY+=.5*s.ortho.scale*(i/c)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=(u-A)/o*i.dragRotationRate/2,r.rotateDeltaX+=(g-h)/c*(i.dragRotationRate/4)):(r.rotateDeltaY-=(u-A)/o*(1.5*i.dragRotationRate),r.rotateDeltaX+=(g-h)/c*(1.5*i.dragRotationRate)));A=u,h=g}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Ou);const i=Ou[0],s=Ou[1];Math.abs(i-c)<3&&Math.abs(s-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Ou,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),c=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||c))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,Nu);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*p;Gu.orthoScale=g,n?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldRight,f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):a?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldForward,f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):l?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldRight,-f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):A?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldForward,-f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):h?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldUp,f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,Hu),Vu))):c&&(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldUp,-f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,Hu)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Nu),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Gu,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Gu),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Ku{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,c=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),d=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||d)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=d,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",u),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(c(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(c(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Wu{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Xu=d.vec3();class Ju{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,c=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer&&--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?c=n.pickResult.worldPos:(h=1,c=null),s.followPointerDirty=!1),c){const t=Math.abs(d.lenVec3(d.subVec3(c,e.camera.eye,Xu)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Zu(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Zu(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Zu(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s-window.scrollX,i[1]=e.clientY-r-window.scrollY}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const qu=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class $u{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),h=d.vec2(),c=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(qu(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));c.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],g=t.touches;if(t.touches.length===p){if(1===p){qu(g[0],l),d.subVec2(l,c[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];qu(t,l),qu(n,A);const a=d.geometricMeanVec2(c[0],c[1]),h=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(c[0],c[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,ed(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(c>-1&&h-c<325?(ed(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),c=-1):d.distVec2(l[0],A)<4&&(ed(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),c=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Uu(this,this._configs),pivotController:new Lu(i,this._configs),panController:new Fu(i),cameraFlight:new Xc(this,{duration:.5})},this._handlers=[new Yu(this.scene,this._controllers,this._configs,this._states,this._updates),new $u(this.scene,this._controllers,this._configs,this._states,this._updates),new ku(this.scene,this._controllers,this._configs,this._states,this._updates),new zu(this.scene,this._controllers,this._configs,this._states,this._updates),new Ku(this.scene,this._controllers,this._configs,this._states,this._updates),new td(this.scene,this._controllers,this._configs,this._states,this._updates),new Wu(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Ju(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",y.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?ld(t):null,n=i&&i.length>0?ld(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r>t;i.sort(Yh);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}Zh=new Int32Array(e),t.sort(qh);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new Th({id:"defaultColorTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Th({id:"defaultMetalRoughTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new Th({id:"defaultNormalsTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new Th({id:"defaultEmissiveTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new Th({id:"defaultOcclusionTexture",texture:new kr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Sh({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||pc),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new Th({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new Sh({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(this.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new ac({id:e.id,model:this,parentTransform:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||hc,i=e.position||cc,s=e.rotation||uc;d.eulerToQuaternion(s,"XYZ",dc),e.meshMatrix=d.composeMat4(i,dc,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=an(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):fc,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];X(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=nn(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Nt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new ca({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new ca({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Ya({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new jl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=Z),this._pickable&&!1!==e.pickable&&(t|=$),this._culled&&!1!==e.culled&&(t|=q),this._clippable&&!1!==e.clippable&&(t|=ee),this._collidable&&!1!==e.collidable&&(t|=te),this._edges&&!1!==e.edges&&(t|=oe),this._xrayed&&!1!==e.xrayed&&(t|=ie),this._highlighted&&!1!==e.highlighted&&(t|=se),this._selected&&!1!==e.selected&&(t|=re),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class _c extends R{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ep.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,B=v.filter((e=>!b[e])),x=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=Pc(e.location,vc),i=Pc(e.direction,vc);A&&d.negateVec3(i),d.subVec3(t,l),r.yUp&&(t=Mc(t),i=Mc(i)),new _r(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new _c(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=Pc(e.location,bc),n=Pc(e.normal,yc),a=Pc(e.up,Bc),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=Mc(o),n=Mc(n),a=Mc(a)),new oo(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,c;if(e.perspective_camera?(a=Pc(e.perspective_camera.camera_view_point,vc),A=Pc(e.perspective_camera.camera_direction,vc),h=Pc(e.perspective_camera.camera_up_vector,vc),r.perspective.fov=e.perspective_camera.field_of_view,c="perspective"):(a=Pc(e.orthogonal_camera.camera_view_point,vc),A=Pc(e.orthogonal_camera.camera_direction,vc),h=Pc(e.orthogonal_camera.camera_up_vector,vc),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,c="ortho"),d.subVec3(a,l),r.yUp&&(a=Mc(a),A=Mc(A),h=Mc(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:d.addVec3(a,A,vc)}else A=d.addVec3(a,A,vc);n?(r.eye=a,r.look=A,r.up=h,r.projection=c):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:c})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=d.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}}function wc(e){return{x:e[0],y:e[1],z:e[2]}}function Pc(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Cc(e){return new Float64Array([e[0],-e[2],e[1]])}function Mc(e){return new Float64Array([e[0],e[2],-e[1]])}const Fc=d.vec3(),Ec=(e,t,i,s)=>{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class Ic extends R{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ce(i,t.origin),this._targetMarker=new ce(i,t.target),this._originWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new de(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new ue(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new ue(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new ue(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new ue(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new pe(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new pe(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new pe(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new pe(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],c=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var u=0,p=s.length;ue.offsetTop+(e.offsetParent&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&c(e.offsetParent));this._onCameraControlHoverSnapOrSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.left=c(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null))}destroy(){this.deactivate(),super.destroy()}}class Tc extends G{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Sc(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new Ic(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,s=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{s&&(i-=t.deltaTime,(!this._delayBeforeRestore||i<=0)&&(e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class Lc{constructor(){}getMetaModel(e,t,i){y.loadJSON(e,(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){y.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){y.loadArraybuffer(e,(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Uc{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=Oc(e,i);return s?t?kc(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=Oc(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=kc(r,[t]),i&&(r=kc(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function Oc(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class Qc extends Nc{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const Hc=d.vec3();class Vc extends R{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Qc(this),this._lookCurve=new Qc(this),this._upCurve=new Qc(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Hc),t.look=this._lookCurve.getPoint(e,Hc),t.up=this._upCurve.getPoint(e,Hc)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e=1;e>1&&(e=1);const i=this.easing?Xc._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,Wc),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,zc),s.look=d.subVec3(zc,Wc,Gc)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Gc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Kc)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,zc),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Gc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Kc)),this._projection2){const t="ortho"===this._projection2?Xc._easeOutExpo(e,0,1,1):Xc._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Jc extends R{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Xc(this),this._t=0,this.state=Jc.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case Jc.SCRUBBING:return;case Jc.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Jc.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Jc.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=Jc.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Jc.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Jc.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=Jc.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Jc.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Jc.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Jc.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Jc.STOPPED=0,Jc.SCRUBBING=1,Jc.PLAYING=2,Jc.PLAYING_TO=3;const Yc=d.vec3(),Zc=d.vec3();d.vec3();const qc=d.vec3([0,-1,0]),$c=d.vec4([0,0,0,1]);class eu extends R{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new Gr(this),this._plane=new cr(this,{geometry:new Vt(this,to({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Wt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new cr(this,{geometry:new Vt(this,eo({size:1,divisions:10})),material:new Wt(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Fr(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),W(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,Yc);const s=-d.dotVec3(i,Yc);d.normalizeVec3(i),d.mulVec3Scalar(i,s,Zc),d.vec3PairToQuaternion(qc,e,$c),this._node.quaternion=$c}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class tu extends Ft{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new nt({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new et(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function iu(e){if(!su(e.width)||!su(e.height)){const t=document.createElement("canvas");t.width=ru(e.width),t.height=ru(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function su(e){return 0==(e&e-1)}function ru(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class ou extends R{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new nt({texture:new kr({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class Au{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const hu=d.vec3();class cu{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!i||i.pickable,h=!i||i.colorize,c=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class fu extends Nc{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class mu extends gc{constructor(e,t={}){super(e,t)}}class _u extends R{constructor(e,t={}){super(e,t),this._skyboxMesh=new cr(this,{geometry:new Vt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Wt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Gr(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class vu{transcode(e,t,i={}){}destroy(){}}const bu=d.vec4(),yu=d.vec4(),Bu=d.vec3(),xu=d.vec3(),wu=d.vec3(),Pu=d.vec4(),Cu=d.vec4(),Mu=d.vec4();class Fu{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,Bu);s=d.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),W(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Xr(this._scene,pr({radius:s})),this._pivotSphere=new cr(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(W(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Wt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,Eu)),i=d.cross3Vec3(t,e.worldUp,Iu);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=Su;t.project.unproject(e,a,Tu,Ru,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,Eu)),h=d.addVec3(t.eye,d.mulVec3Scalar(A,i,Iu),Du);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=d.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),a=this.getPivotPos();d.addVec3(o,a);let l=d.lookAtMat4v(o,a,i.worldUp);l=d.inverseMat4(l);const A=d.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],d.subVec3(i.eye,d.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Uu{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Se;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Ou=d.vec2();class ku{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,c=0,u=0,p=!1;const f=d.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],c=t[3],u=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l){const t=u-A,i=g-h,s=e.camera;if("perspective"===s.projection){const o=Math.abs(p?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/c,r.panDeltaY+=1.5*i*o/c}else r.panDeltaX+=.5*s.ortho.scale*(t/c),r.panDeltaY+=.5*s.ortho.scale*(i/c)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=(u-A)/o*i.dragRotationRate/2,r.rotateDeltaX+=(g-h)/c*(i.dragRotationRate/4)):(r.rotateDeltaY-=(u-A)/o*(1.5*i.dragRotationRate),r.rotateDeltaX+=(g-h)/c*(1.5*i.dragRotationRate)));A=u,h=g}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Ou);const i=Ou[0],s=Ou[1];Math.abs(i-c)<3&&Math.abs(s-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Ou,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),c=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||c))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,Nu);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*p;Gu.orthoScale=g,n?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldRight,f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):a?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldForward,f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):l?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldRight,-f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):A?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldForward,-f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(o.worldUp)):h?(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldUp,f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,Hu),Vu))):c&&(Gu.eye.set(d.addVec3(Nu,d.mulVec3Scalar(o.worldUp,-f,Qu),ju)),Gu.look.set(Nu),Gu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,Hu)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Nu),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Gu,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Gu),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Ku{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,c=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),d=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||d)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=d,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",u),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(c(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(c(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Wu{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Xu=d.vec3();class Ju{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,c=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer&&--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?c=n.pickResult.worldPos:(h=1,c=null),s.followPointerDirty=!1),c){const t=Math.abs(d.lenVec3(d.subVec3(c,e.camera.eye,Xu)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Zu(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(Zu(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function Zu(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s-window.scrollX,i[1]=e.clientY-r-window.scrollY}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const qu=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class $u{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),h=d.vec2(),c=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(qu(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));c.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],g=t.touches;if(t.touches.length===p){if(1===p){qu(g[0],l),d.subVec2(l,c[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];qu(t,l),qu(n,A);const a=d.geometricMeanVec2(c[0],c[1]),h=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(c[0],c[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,ed(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(c>-1&&h-c<325?(ed(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),c=-1):d.distVec2(l[0],A)<4&&(ed(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),c=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Uu(this,this._configs),pivotController:new Lu(i,this._configs),panController:new Fu(i),cameraFlight:new Xc(this,{duration:.5})},this._handlers=[new Yu(this.scene,this._controllers,this._configs,this._states,this._updates),new $u(this.scene,this._controllers,this._configs,this._states,this._updates),new ku(this.scene,this._controllers,this._configs,this._states,this._updates),new zu(this.scene,this._controllers,this._configs,this._states,this._updates),new Ku(this.scene,this._controllers,this._configs,this._states,this._updates),new td(this.scene,this._controllers,this._configs,this._states,this._updates),new Wu(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Ju(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",y.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?ld(t):null,n=i&&i.length>0?ld(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r * Copyright (c) 2022 Niklas von Hertzen diff --git a/dist/xeokit-sdk.min.es5.js b/dist/xeokit-sdk.min.es5.js index c89f7179e..a83ecbe40 100644 --- a/dist/xeokit-sdk.min.es5.js +++ b/dist/xeokit-sdk.min.es5.js @@ -1,4 +1,4 @@ -var e,t=a().mark(jx),i=a().mark(Gx),s=a().mark(tM);function r(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function n(e){for(var t=1;t=0;--r){var n=this.tryEntries[r],o=n.completion;if("root"===n.tryLoc)return s("end");if(n.tryLoc<=this.prev){var a=i.call(n,"catchLoc"),l=i.call(n,"finallyLoc");if(a&&l){if(this.prev=0;--s){var r=this.tryEntries[s];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),w(i),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var s=i.completion;if("throw"===s.type){var r=s.arg;w(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),c}},e}function l(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function u(e){return function(){var t=this,i=arguments;return new Promise((function(s,r){var n=e.apply(t,i);function o(e){l(n,s,r,o,a,"next",e)}function a(e){l(n,s,r,o,a,"throw",e)}o(void 0)}))}}function A(e){return function(e){if(Array.isArray(e))return p(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=d(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var s=0,r=function(){};return{s:r,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw n}}}}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var s,r,n=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(s=i.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return n}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e,t){if(e){if("string"==typeof e)return p(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=new Array(t);i0&&void 0!==arguments[0]?arguments[0]:{};w(this,e),this._id=H.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==i.hideOnMouseDown&&(document.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),i.items&&(this.items=i.items),this._hideOnAction=!1!==i.hideOnAction,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return C(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var s=0,r=i.length;s0,A=t._getNextId(),c=n.getTitle||function(){return n.title||""},h=n.doAction||n.callback||function(){},d=n.getEnabled||function(){return!0},p=n.getShown||function(){return!0},f=new G(A,c,h,d,p);if(f.parentMenu=r,l.items.push(f),u){var v=e(o);f.subMenu=v,v.parentItem=f}t._itemList.push(f),t._itemMap[f.id]=f},A=0,c=a.length;A'),s.push("
    "),i)for(var r=0,n=i.length;r'+d+" [MORE]"):s.push('
  • '+d+"
  • ")}}s.push("
"),s.push("");var p=s.join("");document.body.insertAdjacentHTML("beforeend",p);var f=document.querySelector("."+e.id);e.menuElement=f,f.style["border-radius"]="4px",f.style.display="none",f.style["z-index"]=3e5,f.style.background="white",f.style.border="1px solid black",f.style["box-shadow"]="0 4px 5px 0 gray",f.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var m=0,_=i.length;m<_;m++){var y=i[m].items;if(y)for(var b=function(e,i){var s=y[e],r=s.subMenu;if(s.itemElement=document.getElementById(s.id),!s.itemElement)return console.error("ContextMenu item element not found: "+s.id),"continue";s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=s.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==s.enabled){var i=s.itemElement,r=t.menuElement,n=i.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?v._showMenu(t.id,n.left-200,n.top-1):v._showMenu(t.id,n.right-5,n.top-1),g=t}}else g&&(v._hideMenu(g.id),g=null)})),r||(s.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==s.enabled&&(s.doAction&&s.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==s.enabled&&s.doHover&&s.doHover(v._context)})))},B=0,x=y.length;Bwindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),K=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this.viewer=t,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=s.zoomLevel||2,this._active=!1!==s.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(function(){i._active&&i._visible&&i.update()}))}return C(e,[{key:"update",value:function(){if(this._active&&this._visible&&this._canvasPos){var e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop="".concat(t.bottom-t.top-this._lensCanvas.height-85,"px"):this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);var s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);var r=[(e.left+e.right)/2,(e.top+e.bottom)/2];if(this._snappedCanvasPos){var n=this._snappedCanvasPos[0]-this._canvasPos[0],o=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft="".concat(r[0]+n*this._zoomLevel-10,"px"),this._lensCursorDiv.style.marginTop="".concat(r[1]+o*this._zoomLevel-10,"px")}else this._lensCursorDiv.style.marginLeft="".concat(r[0]-10,"px"),this._lensCursorDiv.style.marginTop="".concat(r[1]-10,"px")}}},{key:"zoomFactor",get:function(){return this._zoomFactor},set:function(e){this._zoomFactor=e,this.update()}},{key:"canvasPos",get:function(){return this._canvasPos},set:function(e){this._canvasPos=e,this.update()}},{key:"snappedCanvasPos",get:function(){return this._snappedCanvasPos},set:function(e){this._snappedCanvasPos=e,this.update()}},{key:"snapped",get:function(){return this._snapped},set:function(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}},{key:"active",get:function(){return this._active},set:function(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"destroy",value:function(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}]),e}(),W=!0,X=W?Float64Array:Float32Array,J=new X(3),Y=new X(16),Z=new X(16),q=new X(4),$={setDoublePrecisionEnabled:function(e){X=(W=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return W},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new X(e||2)},vec3:function(e){return new X(e||3)},vec4:function(e){return new X(e||4)},mat3:function(e){return new X(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new X(16);return 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:function(e){return new X(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,i){for(var s=new X(2),r=0,n=e.length;r>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&s|128]).concat(e[s>>8&255],"-").concat(e[s>>16&255]).concat(e[s>>24&255]).concat(e[255&r]).concat(e[r>>8&255]).concat(e[r>>16&255]).concat(e[r>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,e))},fmod:function(e,t){if(e1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new X(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=$.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=$.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=$.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,s=(t=Array.prototype.slice.call(t)).length;i0&&void 0!==arguments[0]?arguments[0]:new X(16);return 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:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new X(9);return 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:function(e){return 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:function(e,t){return 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:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return $.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],u=e[6],A=e[7],c=e[8],h=e[9],d=e[10],p=e[11],f=e[12],v=e[13],g=e[14],m=e[15],_=t[0],y=t[1],b=t[2],B=t[3],x=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],k=t[11],I=t[12],D=t[13],S=t[14],T=t[15];return i[0]=_*s+y*a+b*c+B*f,i[1]=_*r+y*l+b*h+B*v,i[2]=_*n+y*u+b*d+B*g,i[3]=_*o+y*A+b*p+B*m,i[4]=x*s+w*a+P*c+C*f,i[5]=x*r+w*l+P*h+C*v,i[6]=x*n+w*u+P*d+C*g,i[7]=x*o+w*A+P*p+C*m,i[8]=M*s+F*a+E*c+k*f,i[9]=M*r+F*l+E*h+k*v,i[10]=M*n+F*u+E*d+k*g,i[11]=M*o+F*A+E*p+k*m,i[12]=I*s+D*a+S*c+T*f,i[13]=I*r+D*l+S*h+T*v,i[14]=I*n+D*u+S*d+T*g,i[15]=I*o+D*A+S*p+T*m,i},mulMat3:function(e,t,i){i||(i=new X(9));var s=e[0],r=e[3],n=e[6],o=e[1],a=e[4],l=e[7],u=e[2],A=e[5],c=e[8],h=t[0],d=t[3],p=t[6],f=t[1],v=t[4],g=t[7],m=t[2],_=t[5],y=t[8];return i[0]=s*h+r*f+n*m,i[3]=s*d+r*v+n*_,i[6]=s*p+r*g+n*y,i[1]=o*h+a*f+l*m,i[4]=o*d+a*v+l*_,i[7]=o*p+a*g+l*y,i[2]=u*h+A*f+c*m,i[5]=u*d+A*v+c*_,i[8]=u*p+A*g+c*y,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=t[0],r=t[1],n=t[2],o=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],s=e[14],r=e[8],n=e[13],o=e[12],a=e[9];if(!t||e===t){var l=e[1],u=e[2],A=e[3],c=e[6],h=e[7],d=e[11];return e[1]=i,e[2]=r,e[3]=o,e[4]=l,e[6]=a,e[7]=n,e[8]=u,e[9]=c,e[11]=s,e[12]=A,e[13]=h,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],u=e[8],A=e[9],c=e[10],h=e[11],d=e[12],p=e[13],f=e[14],v=e[15];return d*A*a*r-u*p*a*r-d*o*c*r+n*p*c*r+u*o*f*r-n*A*f*r-d*A*s*l+u*p*s*l+d*i*c*l-t*p*c*l-u*i*f*l+t*A*f*l+d*o*s*h-n*p*s*h-d*i*a*h+t*p*a*h+n*i*f*h-t*o*f*h-u*o*s*v+n*A*s*v+u*i*a*v-t*A*a*v-n*i*c*v+t*o*c*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],l=e[6],u=e[7],A=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],v=e[14],g=e[15],m=i*a-s*o,_=i*l-r*o,y=i*u-n*o,b=s*l-r*a,B=s*u-n*a,x=r*u-n*l,w=A*f-c*p,P=A*v-h*p,C=A*g-d*p,M=c*v-h*f,F=c*g-d*f,E=h*g-d*v,k=1/(m*E-_*F+y*M+b*C-B*P+x*w);return t[0]=(a*E-l*F+u*M)*k,t[1]=(-s*E+r*F-n*M)*k,t[2]=(f*x-v*B+g*b)*k,t[3]=(-c*x+h*B-d*b)*k,t[4]=(-o*E+l*C-u*P)*k,t[5]=(i*E-r*C+n*P)*k,t[6]=(-p*x+v*y-g*_)*k,t[7]=(A*x-h*y+d*_)*k,t[8]=(o*F-a*C+u*w)*k,t[9]=(-i*F+s*C-n*w)*k,t[10]=(p*B-f*y+g*m)*k,t[11]=(-A*B+c*y-d*m)*k,t[12]=(-o*M+a*P-l*w)*k,t[13]=(i*M-s*P+r*w)*k,t[14]=(-p*b+f*_-v*m)*k,t[15]=(A*b-c*_+h*m)*k,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||$.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||$.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(O=new X(3),function(e,t,i,s){return O[0]=e,O[1]=t,O[2]=i,$.translationMat4v(O,s)}),translationMat4s:function(e,t){return $.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return $.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,s){var r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;var n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;var o=s[11];s[8]+=o*e,s[9]+=o*t,s[10]+=o*i;var a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var s,r,n,o,a,l,u=$.normalizeVec4([t[0],t[1],t[2],0],[]),A=Math.sin(e),c=Math.cos(e),h=1-c,d=u[0],p=u[1],f=u[2];return s=d*p,r=p*f,n=f*d,o=d*A,a=p*A,l=f*A,(i=i||$.mat4())[0]=h*d*d+c,i[1]=h*s+l,i[2]=h*n-a,i[3]=0,i[4]=h*s-l,i[5]=h*p*p+c,i[6]=h*r+o,i[7]=0,i[8]=h*n+a,i[9]=h*r-o,i[10]=h*f*f+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,s,r){return $.rotationMat4v(e,[t,i,s],r)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new X(3);return function(t,i,s,r){return e[0]=t,e[1]=i,e[2]=s,$.scalingMat4v(e,r)}}(),scaleMat4c:function(e,t,i,s){return s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s},scaleMat4v:function(e,t){var i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:function(e){return $.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.mat4(),s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,l=r+r,u=n+n,A=s*a,c=s*l,h=s*u,d=r*l,p=r*u,f=n*u,v=o*a,g=o*l,m=o*u;return i[0]=1-(d+f),i[1]=c+m,i[2]=h-g,i[3]=0,i[4]=c-m,i[5]=1-(A+f),i[6]=p+v,i[7]=0,i[8]=h+g,i[9]=p-v,i[10]=1-(A+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=$.clamp,r=e[0],n=e[4],o=e[8],a=e[1],l=e[5],u=e[9],A=e[2],c=e[6],h=e[10];return"XYZ"===t?(i[1]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-u,h),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(o,h),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-A,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-A,h),i[2]=Math.atan2(-n,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[0]=Math.atan2(c,h),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-n,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-u,l),i[1]=Math.atan2(-A,r)):(i[0]=0,i[1]=Math.atan2(o,h))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(o,r)):(i[0]=Math.atan2(-u,h),i[1]=0)),i},composeMat4:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.mat4();return $.quaternionToRotationMat4(t,s),$.scaleMat4v(i,s),$.translateMat4v(e,s),s},decomposeMat4:function(){var e=new X(3),t=new X(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=$.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=$.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var l=$.lenVec3(e);$.determinantMat4(i)<0&&(o=-o),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);var u=1/o,A=1/a,c=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=A,t[5]*=A,t[6]*=A,t[8]*=c,t[9]*=c,t[10]*=c,$.mat4ToQuaternion(t,r),n[0]=o,n[1]=a,n[2]=l,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,s){s||(s=$.mat4());var r,n,o,a,l,u,A,c,h,d,p=e[0],f=e[1],v=e[2],g=i[0],m=i[1],_=i[2],y=t[0],b=t[1],B=t[2];return p===y&&f===b&&v===B?$.identityMat4():(r=p-y,n=f-b,o=v-B,a=m*(o*=d=1/Math.sqrt(r*r+n*n+o*o))-_*(n*=d),l=_*(r*=d)-g*o,u=g*n-m*r,(d=Math.sqrt(a*a+l*l+u*u))?(a*=d=1/d,l*=d,u*=d):(a=0,l=0,u=0),A=n*u-o*l,c=o*a-r*u,h=r*l-n*a,(d=Math.sqrt(A*A+c*c+h*h))?(A*=d=1/d,c*=d,h*=d):(A=0,c=0,h=0),s[0]=a,s[1]=A,s[2]=r,s[3]=0,s[4]=l,s[5]=c,s[6]=n,s[7]=0,s[8]=u,s[9]=h,s[10]=o,s[11]=0,s[12]=-(a*p+l*f+u*v),s[13]=-(A*p+c*f+h*v),s[14]=-(r*p+n*f+o*v),s[15]=1,s)},lookAtMat4c:function(e,t,i,s,r,n,o,a,l){return $.lookAtMat4v([e,t,i],[s,r,n],[o,a,l],[])},orthoMat4c:function(e,t,i,s,r,n,o){o||(o=$.mat4());var a=t-e,l=s-i,u=n-r;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/l,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/u,o[11]=0,o[12]=-(e+t)/a,o[13]=-(s+i)/l,o[14]=-(n+r)/u,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=$.mat4());var s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];$.addVec4(r,s,Y),$.subVec4(r,s,Z);var n=2*s[2],o=Z[0],a=Z[1],l=Z[2];return i[0]=n/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/a,i[6]=0,i[7]=0,i[8]=Y[0]/o,i[9]=Y[1]/a,i[10]=-Y[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/l,i[15]=0,i},frustumMat4:function(e,t,i,s,r,n,o){o||(o=$.mat4());var a=t-e,l=s-i,u=n-r;return o[0]=2*r/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*r/l,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(s+i)/l,o[10]=-(n+r)/u,o[11]=-1,o[12]=0,o[13]=0,o[14]=-n*r*2/u,o[15]=0,o},perspectiveMat4:function(e,t,i,s,r){var n=[],o=[];return n[2]=i,o[2]=s,o[1]=n[2]*Math.tan(e/2),n[1]=-o[1],o[0]=o[1]*t,n[0]=-o[0],$.frustumMat4v(n,o,r)},compareMat4:function(e,t){return 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:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var s,r,n,o,a,l=i||[],u=t.length,A=e[0],c=e[1],h=e[2],d=e[3],p=e[4],f=e[5],v=e[6],g=e[7],m=e[8],_=e[9],y=e[10],b=e[11],B=e[12],x=e[13],w=e[14],P=e[15],C=0;C2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2];e[3];var c=e[4],h=e[5],d=e[6];e[7];var p=e[8],f=e[9],v=e[10];e[11];var g=e[12],m=e[13],_=e[14];for(e[15],i=0;i2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],B=e[14],x=e[15];for(i=0;i3&&void 0!==arguments[3]?arguments[3]:e,r=Math.cos(i),n=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return s[0]=o*r-a*n+t[0],s[1]=o*n+a*r+t[1],e},rotateVec3X:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4:function(e,t){var i=1/e[3];return(t=t||$.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(R=new X(16),L=new X(16),U=new X(16),function(e,t,i,s){return this.transformVec3(this.mulMat4(this.inverseMat4(t,R),this.inverseMat4(i,L),U),e,s)}),lerpVec3:function(e,t,i,s,r,n){var o=n||$.vec3(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o},lerpMat4:function(e,t,i,s,r,n){var o=n||$.mat4(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o[3]=s[3]+a*(r[3]-s[3]),o[4]=s[4]+a*(r[4]-s[4]),o[5]=s[5]+a*(r[5]-s[5]),o[6]=s[6]+a*(r[6]-s[6]),o[7]=s[7]+a*(r[7]-s[7]),o[8]=s[8]+a*(r[8]-s[8]),o[9]=s[9]+a*(r[9]-s[9]),o[10]=s[10]+a*(r[10]-s[10]),o[11]=s[11]+a*(r[11]-s[11]),o[12]=s[12]+a*(r[12]-s[12]),o[13]=s[13]+a*(r[13]-s[13]),o[14]=s[14]+a*(r[14]-s[14]),o[15]=s[15]+a*(r[15]-s[15]),o},flatten:function(e){var t,i,s,r,n,o=[];for(t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:$.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=e[0]*$.DEGTORAD/2,r=e[1]*$.DEGTORAD/2,n=e[2]*$.DEGTORAD/2,o=Math.cos(s),a=Math.cos(r),l=Math.cos(n),u=Math.sin(s),A=Math.sin(r),c=Math.sin(n);return"XYZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"YXZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"ZXY"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"ZYX"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"YZX"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l-u*A*c):"XZY"===t&&(i[0]=u*a*l-o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l+u*A*c),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),s=e[0],r=e[4],n=e[8],o=e[1],a=e[5],l=e[9],u=e[2],A=e[6],c=e[10],h=s+a+c;return h>0?(t=.5/Math.sqrt(h+1),i[3]=.25/t,i[0]=(A-l)*t,i[1]=(n-u)*t,i[2]=(o-r)*t):s>a&&s>c?(t=2*Math.sqrt(1+s-a-c),i[3]=(A-l)/t,i[0]=.25*t,i[1]=(r+o)/t,i[2]=(n+u)/t):a>c?(t=2*Math.sqrt(1+a-s-c),i[3]=(n-u)/t,i[0]=(r+o)/t,i[1]=.25*t,i[2]=(l+A)/t):(t=2*Math.sqrt(1+c-s-a),i[3]=(o-r)/t,i[0]=(n+u)/t,i[1]=(l+A)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=Math.sqrt($.dotVec3(e,e)*$.dotVec3(t,t)),r=s+$.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):$.cross3Vec3(e,t,i),i[3]=r,$.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new X(16);return function(t,i,s){return s=s||$.vec3(),$.quaternionToRotationMat4(t,e),$.mat4ToEuler(e,i,s),s}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=e[0],r=e[1],n=e[2],o=e[3],a=t[0],l=t[1],u=t[2],A=t[3];return i[0]=o*a+s*A+r*u-n*l,i[1]=o*l+r*A+n*a-s*u,i[2]=o*u+n*A+s*l-r*a,i[3]=o*A-s*a-r*l-n*u,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),s=t[0],r=t[1],n=t[2],o=e[0],a=e[1],l=e[2],u=e[3],A=u*s+a*n-l*r,c=u*r+l*s-o*n,h=u*n+o*r-a*s,d=-o*s-a*r-l*n;return i[0]=A*u+d*-o+c*-l-h*-a,i[1]=c*u+d*-a+h*-o-A*-l,i[2]=h*u+d*-l+A*-a-c*-o,i},quaternionToMat4:function(e,t){t=$.identityMat4(t);var i=e[0],s=e[1],r=e[2],n=e[3],o=2*i,a=2*s,l=2*r,u=o*n,A=a*n,c=l*n,h=o*i,d=a*i,p=l*i,f=a*s,v=l*s,g=l*r;return t[0]=1-(f+g),t[1]=d+c,t[2]=p-A,t[4]=d-c,t[5]=1-(h+g),t[6]=v+u,t[8]=p+A,t[9]=v-u,t[10]=1-(h+f),t},quaternionToRotationMat4:function(e,t){var i=e[0],s=e[1],r=e[2],n=e[3],o=i+i,a=s+s,l=r+r,u=i*o,A=i*a,c=i*l,h=s*a,d=s*l,p=r*l,f=n*o,v=n*a,g=n*l;return t[0]=1-(h+p),t[4]=A-g,t[8]=c+v,t[1]=A+g,t[5]=1-(u+p),t[9]=d-f,t[2]=c-v,t[6]=d+f,t[10]=1-(u+h),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=$.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return $.normalizeQuaternion($.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=(e=$.normalizeQuaternion(e,q))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:function(e){return new X(e||6)},AABB2:function(e){return new X(e||4)},OBB3:function(e){return new X(e||32)},OBB2:function(e){return new X(e||16)},Sphere3:function(e,t,i,s){return new X([e,t,i,s])},transformOBB3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],B=e[14],x=e[15];for(i=0;ia?o:a,n[1]+=l>u?l:u,n[2]+=A>c?A:c,Math.abs($.lenVec3(n))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||$.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||$.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$.AABB3();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MAX_DOUBLE,e[3]=$.MIN_DOUBLE,e[4]=$.MIN_DOUBLE,e[5]=$.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.OBB3();return 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:function(){var e=new X(3);return function(t,i,s){i=i||$.AABB3();for(var r,n,o,a=$.MAX_DOUBLE,l=$.MAX_DOUBLE,u=$.MAX_DOUBLE,A=$.MIN_DOUBLE,c=$.MIN_DOUBLE,h=$.MIN_DOUBLE,d=0,p=t.length;dA&&(A=r),n>c&&(c=n),o>h&&(h=o);return i[0]=a,i[1]=l,i[2]=u,i[3]=A,i[4]=c,i[5]=h,i}}(),OBB3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),s>A&&(A=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r[4]=u,r[5]=A,r},points3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),s>A&&(A=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r[4]=u,r[5]=A,r},points3ToSphere3:function(){var e=new X(3);return function(t,i){i=i||$.vec4();var s,r=0,n=0,o=0,a=t.length;for(s=0;su&&(u=l);return i[3]=u,i}}(),positions3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,s){s=s||$.vec4();var r,n=0,o=0,a=0,l=i.length,u=0;for(r=0;ru&&(u=A);return s[3]=u,s}}(),OBB3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,s){s=s||$.vec4();var r,n=0,o=0,a=0,l=i.length,u=l/4;for(r=0;rc&&(c=A);return s[3]=c,s}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(),i=0,s=0,r=0,n=0,o=e.length;nt[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[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]0&&void 0!==arguments[0]?arguments[0]:$.AABB2();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MIN_DOUBLE,e[3]=$.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB2(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MIN_DOUBLE,l=$.MIN_DOUBLE,u=0,A=e.length;ua&&(a=t),i>l&&(l=i);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]3&&void 0!==arguments[3]?arguments[3]:e,r=.5*(e[0]+1),n=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(o*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:function(e,t,i,s){return 2*(1-e)*(i-t)+2*e*(s-i)},tangentQuadraticBezier3:function(e,t,i,s,r){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,i,s,r){var n=.5*(i-e),o=.5*(s-t),a=r*r;return(2*t-2*i+n+o)*(r*a)+(-3*t+3*i-2*n-o)*a+n*r+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.vec3(),r=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],u=i[2]-e[2],A=n*u-o*l,c=o*a-r*u,h=r*l-n*a,d=Math.sqrt(A*A+c*c+h*h);return 0===d?(s[0]=0,s[1]=0,s[2]=0):(s[0]=A/d,s[1]=c/d,s[2]=h/d),s},rayTriangleIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),s=new X(3),r=new X(3);return function(n,o,a,l,u,A){A=A||$.vec3();var c=$.subVec3(l,a,e),h=$.subVec3(u,a,t),d=$.cross3Vec3(o,h,i),p=$.dotVec3(c,d);if(p<1e-6)return null;var f=$.subVec3(n,a,s),v=$.dotVec3(f,d);if(v<0||v>p)return null;var g=$.cross3Vec3(f,c,r),m=$.dotVec3(o,g);if(m<0||v+m>p)return null;var _=$.dotVec3(h,g)/p;return A[0]=n[0]+_*o[0],A[1]=n[1]+_*o[1],A[2]=n[2]+_*o[2],A}}(),rayPlaneIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),s=new X(3);return function(r,n,o,a,l,u){u=u||$.vec3(),n=$.normalizeVec3(n,e);var A=$.subVec3(a,o,t),c=$.subVec3(l,o,i),h=$.cross3Vec3(A,c,s);$.normalizeVec3(h,h);var d=-$.dotVec3(o,h),p=-($.dotVec3(r,h)+d)/$.dotVec3(n,h);return u[0]=r[0]+p*n[0],u[1]=r[1]+p*n[1],u[2]=r[2]+p*n[2],u}}(),cartesianToBarycentric:function(){var e=new X(3),t=new X(3),i=new X(3);return function(s,r,n,o,a){var l=$.subVec3(o,r,e),u=$.subVec3(n,r,t),A=$.subVec3(s,r,i),c=$.dotVec3(l,l),h=$.dotVec3(l,u),d=$.dotVec3(l,A),p=$.dotVec3(u,u),f=$.dotVec3(u,A),v=c*p-h*h;if(0===v)return null;var g=1/v,m=(p*d-h*f)*g,_=(c*f-h*d)*g;return a[0]=1-m-_,a[1]=_,a[2]=m,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,s){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:$.vec3(),n=e[0],o=e[1],a=e[2];return r[0]=t[0]*n+i[0]*o+s[0]*a,r[1]=t[1]*n+i[1]*o+s[1]*a,r[2]=t[2]*n+i[2]*o+s[2]*a,r},mergeVertices:function(e,t,i,s){var r,n,o,a,l,u,A={},c=[],h=[],d=t?[]:null,p=i?[]:null,f=[],v=Math.pow(10,4),g=0;for(l=0,u=e.length;l>24&255,o=c>>16&255,n=c>>8&255,r=255&c,s=3*t[p],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,s=3*t[p+1],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,s=3*t[p+2],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,c++;return{positions:u,colors:A}},faceToVertexNormals:function(e,t){var i,s,r,n,o,a,l,u,A,c,h,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},p=d.smoothNormalsAngleThreshold||20,f={},v=[],g={},m=4,_=Math.pow(10,m);for(l=0,A=e.length;ll[3]&&(l[3]=r[h]),r[h+1]l[4]&&(l[4]=r[h+1]),r[h+2]l[5]&&(l[5]=r[h+2])}if(i.length<20||n>10)return u.triangles=i,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),u.splitDim=d;var p=(l[d]+l[d+3])/2,f=new Array(i.length),v=0,g=new Array(i.length),m=0;for(o=0,a=i.length;o2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s:function(e,t){for(var i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/l,t[s+1]=o/l,t[s+2]=a/l,s+=3}return t}};$.buildEdgeIndices=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(r,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=r.length;AI)||(F=i[P.index1],E=i[P.index2],(!S&&F>65535||E>65535)&&(S=!0),k.push(F),k.push(E));return S?new Uint32Array(k):new Uint16Array(k)}}(),$.planeClipsPositions3=function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:3,r=0,n=i.length;r=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&$.containsAABB3(e.left.aabb,s))this._insertEntity(e.left,t,i+1);else if(e.right&&$.containsAABB3(e.right.aabb,s))this._insertEntity(e.right,t,i+1);else{var r=e.aabb;ee[0]=r[3]-r[0],ee[1]=r[4]-r[1],ee[2]=r[5]-r[2];var n=0;if(ee[1]>ee[n]&&(n=1),ee[2]>ee[n]&&(n=2),!e.left){var o=r.slice();if(o[n+3]=(r[n]+r[n+3])/2,e.left={aabb:o},$.containsAABB3(o,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){var a=r.slice();if(a[n]=(r[n]+r[n+3])/2,e.right={aabb:a},$.containsAABB3(a,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}}},{key:"destroy",value:function(){var e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}]),e}(),ie=function(){function e(){w(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return C(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var 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}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),se={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 re=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r1&&void 0!==arguments[1]?arguments[1]:null;ce.push(e),ce.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,s=(new Date).getTime(),r=0;ce.length>0&&(i<0||s0&&ae>0){var t=1e3/ae;fe+=t,de.push(t),de.length>=30&&(fe-=de.shift()),se.frame.fps=Math.round(fe/de.length)}for(var i in _e.scenes)_e.scenes[i].compile();be(e),pe=e};ve=function(){ye()},ge=100,me=Date.now()+ge,function e(){var t=Date.now()-me;ve(),me+=ge,setTimeout(e,Math.max(0,ge-t))}();function be(e){var t=_e.runTasks(e+10),i=_e.getNumTasks();se.frame.tasksRun=t,se.frame.tasksScheduled=i,se.frame.tasksBudget=10}!function e(){var t=Date.now();if(ae=t-pe,pe>0&&ae>0){var i=1e3/ae;fe+=i,de.push(i),de.length>=30&&(fe-=de.shift()),se.frame.fps=Math.round(fe/de.length)}be(t),function(e){for(var t in he.time=e,_e.scenes)if(_e.scenes.hasOwnProperty(t)){var i=_e.scenes[t];he.sceneId=t,he.startTime=i.startTime,he.deltaTime=null!=he.prevTime?he.time-he.prevTime:0,i.fire("tick",he,!0)}he.prevTime=e}(t),function(){var e,t,i,s,r,n=_e.scenes,o=!1;for(r in n)n.hasOwnProperty(r)&&(e=n[r],(t=ue[r])||(t=ue[r]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),s=e.ticksPerRender,t.ticksPerRender!==s&&(t.ticksPerRender=s,t.renderCountdown=s),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=s))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(ye):requestAnimationFrame(e)}();var Be=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.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,t&&t._own(this)}return C(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Q),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+le.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var i=e.component,s=e.sceneDefault,r=e.sceneSingleton,n=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(le.isNumeric(i)||le.isString(i))){var l=i;if(!(i=this.scene.components[l]))return void this.error("Component not found: "+le.inQuotes(l))}if(!i)if(!0===r){var u=this.scene.types[n];for(var A in u)if(u.hasOwnProperty){i=u[A];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+le.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+le.inQuotes(i.id))}this._attachments||(this._attachments={});var c,h,d,p=this._attached[t];if(p){if(i&&p.id===i.id)return;var f=this._attachments[p.id];for(h=0,d=(c=f.subs).length;h=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Me=C((function e(){w(this,e),this.planes=[new Ce,new Ce,new Ce,new Ce,new Ce,new Ce]}));function Fe(e,t,i){var s=$.mulMat4(i,t,Pe),r=s[0],n=s[1],o=s[2],a=s[3],l=s[4],u=s[5],A=s[6],c=s[7],h=s[8],d=s[9],p=s[10],f=s[11],v=s[12],g=s[13],m=s[14],_=s[15];e.planes[0].set(a-r,c-l,f-h,_-v),e.planes[1].set(a+r,c+l,f+h,_+v),e.planes[2].set(a-n,c-u,f-d,_-g),e.planes[3].set(a+n,c+u,f+d,_+g),e.planes[4].set(a-o,c-A,f-p,_-m),e.planes[5].set(a+o,c+A,f+p,_+m)}function Ee(e,t){var i=Me.INSIDE,s=xe,r=we;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];for(var n=[s,r],o=0;o<6;++o){var a=e.planes[o];if(a.normal[0]*n[a.testVertex[0]][0]+a.normal[1]*n[a.testVertex[1]][1]+a.normal[2]*n[a.testVertex[2]][2]+a.offset<0)return Me.OUTSIDE;a.normal[0]*n[1-a.testVertex[0]][0]+a.normal[1]*n[1-a.testVertex[1]][1]+a.normal[2]*n[1-a.testVertex[2]][2]+a.offset<0&&(i=Me.INTERSECT)}return i}Me.INSIDE=0,Me.INTERSECT=1,Me.OUTSIDE=2;var ke=function(e){g(i,Be);var t=_(i);function i(){var e,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(w(this,i),!s.viewer)throw"[MarqueePicker] Missing config: viewer";if(!s.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";return(e=t.call(this,s.viewer.scene,s)).viewer=s.viewer,e._objectsKdTree3=s.objectsKdTree3,e._canvasMarqueeCorner1=$.vec2(),e._canvasMarqueeCorner2=$.vec2(),e._canvasMarquee=$.AABB2(),e._marqueeFrustum=new Me,e._marqueeFrustumProjMat=$.mat4(),e._pickMode=!1,e._marqueeElement=document.createElement("div"),document.body.appendChild(e._marqueeElement),e._marqueeElement.style.position="absolute",e._marqueeElement.style["z-index"]="40000005",e._marqueeElement.style.width="8px",e._marqueeElement.style.height="8px",e._marqueeElement.style.visibility="hidden",e._marqueeElement.style.top="0px",e._marqueeElement.style.left="0px",e._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",e._marqueeElement.style.opacity=1,e._marqueeElement.style["pointer-events"]="none",e}return C(i,[{key:"setMarqueeCorner1",value:function(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarqueeCorner2",value:function(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarquee",value:function(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}},{key:"setMarqueeVisible",value:function(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}},{key:"getMarqueeVisible",value:function(){return this._marqueVisible}},{key:"setPickMode",value:function(e){if(e!==i.PICK_MODE_INSIDE&&e!==i.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===i.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}},{key:"getPickMode",value:function(){return this._pickMode}},{key:"clear",value:function(){this.fire("clear",{})}},{key:"pick",value:function(){var e=this;this._updateMarquee(),this._buildMarqueeFrustum();var t=[];return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&function s(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Me.INTERSECT;if(n===Me.INTERSECT&&(n=Ee(e._marqueeFrustum,r.aabb)),n!==Me.OUTSIDE){if(r.entities)for(var o=r.entities,a=0,l=o.length;a3||i>3)&&c.pick()}})),document.addEventListener("mouseup",(function(e){s.getActive()&&0===e.button&&(clearTimeout(A),d&&(c.setMarqueeVisible(!1),d=!1,p=!1,f=!0,c.viewer.cameraControl.pointerEnabled=!0))}),!0),h.addEventListener("mousemove",(function(e){s.getActive()&&0===e.button&&p&&(clearTimeout(A),d&&(o=e.pageX,a=e.pageY,u=e.offsetX,c.setMarqueeVisible(!0),c.setMarqueeCorner2([o,a]),c.setPickMode(l0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),Se=$.vec3(),Te=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,$.transformVec4(s,t,i),$.setMat4Translation(s,i,n),n.slice()}}();function Re(e,t,i){var s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],o=e[1]-n,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=n,t[2]=a,i[0]=r,i[1]=o,i[2]=l}function Le(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,r=$.getPositionsCenter(e,Se),n=Math.round(r[0]/s)*s,o=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=n,i[1]=o,i[2]=a;var l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(var u=0,A=e.length;u0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._color=s.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=s.thickness||1,this._thicknessClickable=s.thicknessClickable||6,this._visible=!0,this._culled=!1;var r=this._wire,n=r.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===s.zIndex?"2000001":s.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._wireClickable,a=o.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===s.zIndex?"2000002":s.zIndex+1,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onMouseWheel&&o.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&o.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&o.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&o.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return C(e,[{key:"visible",get:function(){return"visible"===this._wire.style.visibility}},{key:"_update",value:function(){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,i=this._wire.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)";var s=this._wireClickable.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)"}},{key:"setStartAndEnd",value:function(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}},{key:"setColor",value:function(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}},{key:"setOpacity",value:function(e){this._wire.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}},{key:"destroy",value:function(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),tt=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!s.visible,this._culled=!1;var r=this._dot,n=r.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"40000005":s.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==s.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._dotClickable,a=o.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===s.zIndex?"40000007":s.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),o.addEventListener("click",(function(e){t.dispatchEvent(new MouseEvent("mouseover",e))})),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),t.dispatchEvent(new MouseEvent("mouseover",e))})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onMouseWheel&&o.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&o.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&o.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&o.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.borderColor)}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}},{key:"setFillColor",value:function(e){this._dot.style.background=e||"lightgreen"}},{key:"setBorderColor",value:function(e){this._dot.style.border="solid 2px"+(e||"black")}},{key:"setOpacity",value:function(e){this._dot.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}},{key:"destroy",value:function(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),it=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=s.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 r=this._label,n=r.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"5000005":s.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,s.onContextMenu,r.innerText="",t.appendChild(r),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.fillColor),this.setText(s.text),s.onMouseOver&&r.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),e.preventDefault()})),s.onMouseLeave&&r.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i),e.preventDefault()})),s.onMouseWheel&&r.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&r.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&r.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&r.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&r.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()}))}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,i,s){var r=e+.5*(i-e),n=t+.5*(s-t),o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(n)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,i,s,r,n){var o=(e+i+r)/3,a=(t+s+n)/3,l=this._label.style;l.left=Math.round(o)-20+"px",l.top=Math.round(a)-12+"px"}},{key:"setText",value:function(e){this._label.innerHTML=this._prefix+(e||"")}},{key:"setFillColor",value:function(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}},{key:"setBorderColor",value:function(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}},{key:"setOpacity",value:function(e){this._label.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}},{key:"setClickable",value:function(e){this._label.style["pointer-events"]=e?"all":"none"}},{key:"destroy",value:function(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}]),e}(),st=$.vec3(),rt=$.vec3(),nt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._color=r.color||e.defaultColor;var n=s.plugin.viewer.scene;s._originMarker=new $e(n,r.origin),s._cornerMarker=new $e(n,r.corner),s._targetMarker=new $e(n,r.target),s._originWorld=$.vec3(),s._cornerWorld=$.vec3(),s._targetWorld=$.vec3(),s._wp=new Float64Array(12),s._vp=new Float64Array(12),s._pp=new Float64Array(12),s._cp=new Int16Array(6);var o=r.onMouseOver?function(e){r.onMouseOver(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=r.onContextMenu?function(e){r.onContextMenu(e,b(s))}:null,u=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},A=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},c=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},h=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};return s._originDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._cornerDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._targetDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._originWire=new et(s._container,{color:s._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._targetWire=new et(s._container,{color:s._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._angleLabel=new it(s._container,{fillColor:s._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._visible=!1,s._originVisible=!1,s._cornerVisible=!1,s._targetVisible=!1,s._originWireVisible=!1,s._targetWireVisible=!1,s._angleVisible=!1,s._labelsVisible=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._cornerMarker.on("worldPos",(function(e){s._cornerWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){s._sectionPlanesDirty=!0,s._needUpdate()})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.cornerVisible=r.cornerVisible,s.targetVisible=r.targetVisible,s.originWireVisible=r.originWireVisible,s.targetWireVisible=r.targetWireVisible,s.angleVisible=r.angleVisible,s.labelsVisible=r.labelsVisible,s}return C(i,[{key:"_update",value:function(){if(this._visible){var 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&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){var t=-.3,i=this._originMarker.viewPos[2],s=this._cornerMarker.viewPos[2],r=this._targetMarker.viewPos[2];if(i>t||s>t||r>t)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);$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var n=this._pp,o=this._cp,a=e.canvas.canvas.getBoundingClientRect(),l=this._container.getBoundingClientRect(),u=a.top-l.top,A=a.left-l.left,c=e.canvas.boundary,h=c[2],d=c[3],p=0,f=0,v=n.length;f1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e.viewer.scene)).pointerLens=r.pointerLens,s._active=!1,s._mouseState=0,s._currentAngleMeasurement=null,s._initMarkerDiv(),s._onMouseHoverSurface=null,s._onHoverNothing=null,s._onPickedNothing=null,s._onPickedSurface=null,s._onInputMouseDown=null,s._onInputMouseUp=null,s._snapping=!1!==r.snapping,s._attachPlugin(e,r),s}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this.markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.angleMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this.markerDiv||this._initMarkerDiv(),this.angleMeasurementsPlugin;var t=this.scene;t.input;var i=t.canvas.canvas,s=this.angleMeasurementsPlugin.viewer.cameraControl,r=this.pointerLens,n=!1,o=null,a=0,l=0,u=$.vec3(),A=$.vec2();this._currentAngleMeasurement=null,this._onMouseHoverSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){t.snappedToVertex||t.snappedToEdge?(r&&(r.visible=!0,r.canvasPos=t.canvasPos,r.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,r.snapped=!0),e.markerDiv.style.background="greenyellow",e.markerDiv.style.border="2px solid green"):(r&&(r.visible=!0,r.canvasPos=t.canvasPos,r.snappedCanvasPos=t.canvasPos,r.snapped=!1),e.markerDiv.style.background="pink",e.markerDiv.style.border="2px solid red");var s=t.snappedCanvasPos||t.canvasPos;switch(n=!0,o=t.entity,u.set(t.worldPos),A.set(s),e._mouseState){case 0:var a=i.getBoundingClientRect(),l=window.pageXOffset||document.documentElement.scrollLeft,c=window.pageYOffset||document.documentElement.scrollTop,h=a.left+l,d=a.top+c;e.markerDiv.style.left="".concat(h+s[0]-5,"px"),e.markerDiv.style.top="".concat(d+s[1]-5,"px");break;case 1:e._currentAngleMeasurement&&(e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.worldPos=t.worldPos,e._currentAngleMeasurement.corner.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer";break;case 2:e._currentAngleMeasurement&&(e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.worldPos=t.worldPos,e._currentAngleMeasurement.target.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer"}})),i.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=function(t){if(1===t.which&&!(t.clientX>a+20||t.clientXl+20||t.clientY1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"AngleMeasurements",e))._container=r.container||document.body,s._defaultControl=null,s._measurements={},s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.zIndex=r.zIndex||1e4,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new at(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,s=t.corner,r=t.target,n=new nt(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:r.entity,worldPos:r.worldPos},visible:t.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[n.id]=n,n.on("destroyed",(function(){delete e._measurements[n.id]})),n.clickable=!0,this.fire("measurementCreated",n),n}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t

";le.isArray(t)&&(t=t.join("")),t=this._renderTemplate(t.trim());var i=document.createRange().createContextualFragment(t);this._marker=i.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(function(){e.plugin.fire("markerClicked",e)})),this._marker.addEventListener("mouseenter",(function(){e.plugin.fire("markerMouseEnter",e)})),this._marker.addEventListener("mouseleave",(function(){e.plugin.fire("markerMouseLeave",e)})),this._marker.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);var s=this._labelHTML||"

";le.isArray(s)&&(s=s.join("")),s=this._renderTemplate(s.trim());var r=document.createRange().createContextualFragment(s);this._label=r.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}},{key:"setMarkerShown",value:function(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}},{key:"getMarkerShown",value:function(){return this._markerShown}},{key:"setLabelShown",value:function(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}},{key:"getLabelShown",value:function(){return this._labelShown}},{key:"setField",value:function(e,t){this._values[e]=t||"",this._htmlDirty=!0}},{key:"getField",value:function(e){return this._values[e]}},{key:"setValues",value:function(e){for(var t in e)if(e.hasOwnProperty(t)){var i=e[t];this.setField(t,i)}}},{key:"getValues",value:function(){return this._values}},{key:"destroy",value:function(){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),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),At=$.vec3(),ct=$.vec3(),ht=$.vec3(),dt=function(e){g(i,De);var t=_(i);function i(e,s){var r;return w(this,i),(r=t.call(this,"Annotations",e))._labelHTML=s.labelHTML||"
",r._markerHTML=s.markerHTML||"
",r._container=s.container||document.body,r._values=s.values||{},r.annotations={},r.surfaceOffset=s.surfaceOffset,r}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){if("clearAnnotations"===e)this.clear()}},{key:"surfaceOffset",get:function(){return this._surfaceOffset},set:function(e){null==e&&(e=.3),this._surfaceOffset=e}},{key:"createAnnotation",value:function(e){var t,i,s=this;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){var r=e.pickResult;if(r.worldPos&&r.worldNormal){var n=$.normalizeVec3(r.worldNormal,At),o=$.mulVec3Scalar(n,this._surfaceOffset,ct);t=$.addVec3(r.worldPos,o,ht),i=r.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var a=null;e.markerElementId&&((a=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var l=null;e.labelElementId&&((l=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var u=new ut(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:a,labelElement:l,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:le.apply(e.values,le.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[u.id]=u,u.on("destroyed",(function(){delete s.annotations[u.id],s.fire("annotationDestroyed",u.id)})),this.fire("annotationCreated",u.id),u}},{key:"destroyAnnotation",value:function(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}},{key:"clear",value:function(){for(var e=Object.keys(this.annotations),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._canvas=r.canvas,s._element=null,s._isCustom=!1,r.elementId&&(s._element=document.getElementById(r.elementId),s._element?s._adjustPosition():s.error("Can't find given Spinner HTML element: '"+r.elementId+"' - will automatically create default element")),s._element||s._createDefaultSpinner(),s.processes=0,s}return C(i,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var 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)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),i}(),ft=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],vt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._backgroundColor=$.vec3([r.backgroundColor?r.backgroundColor[0]:1,r.backgroundColor?r.backgroundColor[1]:1,r.backgroundColor?r.backgroundColor[2]:1]),s._backgroundColorFromAmbientLight=!!r.backgroundColorFromAmbientLight,s.canvas=r.canvas,s.gl=null,s.webgl2=!1,s.transparent=!!r.transparent,s.contextAttr=r.contextAttr||{},s.contextAttr.alpha=s.transparent,s.contextAttr.preserveDrawingBuffer=!!s.contextAttr.preserveDrawingBuffer,s.contextAttr.stencil=!1,s.contextAttr.premultipliedAlpha=!!s.contextAttr.premultipliedAlpha,s.contextAttr.antialias=!1!==s.contextAttr.antialias,s.resolutionScale=r.resolutionScale,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary=[s.canvas.offsetLeft,s.canvas.offsetTop,s.canvas.clientWidth,s.canvas.clientHeight],s._initWebGL(r);var n=b(s);s.canvas.addEventListener("webglcontextlost",s._webglcontextlostListener=function(e){console.time("webglcontextrestored"),n.scene._webglContextLost(),n.fire("webglcontextlost"),e.preventDefault()},!1),s.canvas.addEventListener("webglcontextrestored",s._webglcontextrestoredListener=function(e){n._initWebGL(),n.gl&&(n.scene._webglContextRestored(n.gl),n.fire("webglcontextrestored",n.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=!0,a=new ResizeObserver((function(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){t.value.contentBoxSize&&(o=!0)}}catch(e){i.e(e)}finally{i.f()}}));return a.observe(s.canvas),s._tick=s.scene.on("tick",(function(){o&&(o=!1,n.canvas.width=Math.round(n.canvas.clientWidth*n._resolutionScale),n.canvas.height=Math.round(n.canvas.clientHeight*n._resolutionScale),n.boundary[0]=n.canvas.offsetLeft,n.boundary[1]=n.canvas.offsetTop,n.boundary[2]=n.canvas.clientWidth,n.boundary[3]=n.canvas.clientHeight,n.fire("boundary",n.boundary))})),s._spinner=new pt(s.scene,{canvas:s.canvas,elementId:r.spinnerElementId}),s}return C(i,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(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()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+$.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e0?mt.FS_MAX_FLOAT_PRECISION="highp":yt.getShaderPrecisionFormat(yt.FRAGMENT_SHADER,yt.MEDIUM_FLOAT).precision>0?mt.FS_MAX_FLOAT_PRECISION="mediump":mt.FS_MAX_FLOAT_PRECISION="lowp":mt.FS_MAX_FLOAT_PRECISION="mediump",mt.DEPTH_BUFFER_BITS=yt.getParameter(yt.DEPTH_BITS),mt.MAX_TEXTURE_SIZE=yt.getParameter(yt.MAX_TEXTURE_SIZE),mt.MAX_CUBE_MAP_SIZE=yt.getParameter(yt.MAX_CUBE_MAP_TEXTURE_SIZE),mt.MAX_RENDERBUFFER_SIZE=yt.getParameter(yt.MAX_RENDERBUFFER_SIZE),mt.MAX_TEXTURE_UNITS=yt.getParameter(yt.MAX_COMBINED_TEXTURE_IMAGE_UNITS),mt.MAX_TEXTURE_IMAGE_UNITS=yt.getParameter(yt.MAX_TEXTURE_IMAGE_UNITS),mt.MAX_VERTEX_ATTRIBS=yt.getParameter(yt.MAX_VERTEX_ATTRIBS),mt.MAX_VERTEX_UNIFORM_VECTORS=yt.getParameter(yt.MAX_VERTEX_UNIFORM_VECTORS),mt.MAX_FRAGMENT_UNIFORM_VECTORS=yt.getParameter(yt.MAX_FRAGMENT_UNIFORM_VECTORS),mt.MAX_VARYING_VECTORS=yt.getParameter(yt.MAX_VARYING_VECTORS),yt.getSupportedExtensions().forEach((function(e){mt.SUPPORTED_EXTENSIONS[e]=!0})))}var bt=function(){function e(){w(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return C(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"snappedCanvasPos",get:function(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null},set:function(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}]),e}(),Bt=function(){function e(t,i,s){if(w(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,s),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var r=s.split("\n"),n=[],o=0;o0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),s.push(t);return s.join("\n")}function Mt(e){console.error(e.join("\n"))}var Ft=function(){function e(t,i){w(this,e),this.id=Pt.addItem({}),this.source=i,this.init(t)}return C(e,[{key:"init",value:function(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 Bt(e,e.VERTEX_SHADER,Ct(this.source.vertex)),this._fragmentShader=new Bt(e,e.FRAGMENT_SHADER,Ct(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Mt(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Mt(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Mt(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Mt(this.errors);var t,i,s,r,n;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){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 Mt(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.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)}},{key:"setData",value:function(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)))}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),kt=function(){function e(t,i){w(this,e),this.scene=t,this.aabb=$.AABB3(),this.origin=$.vec3(i),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}return C(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var 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}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){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()}},{key:"_buildMarkerList",value:function(){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}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t-t)a._setVisible(!1);else{var l=a.canvasPos,u=l[0],A=l[1];u+10<0||A+10<0||u-10>s||A-10>r?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[n++]=u,this.pixels[n++]=A):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ft(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r0)for(var h=s.sectionPlanes,d=0;d= ( 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);var s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Et(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Et(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Et(i,i.ELEMENT_ARRAY_BUFFER,n,n.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),Lt=new Float32Array(Vt(17,[0,1])),Ut=new Float32Array(Vt(17,[1,0])),Ot=new Float32Array(function(e,t){for(var i=[],s=0;s<=e;s++)i.push(Ht(s,t));return i}(17,4)),Nt=new Float32Array(2),Qt=function(){function e(t){w(this,e),this._scene=t,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()}return C(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new Ft(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 ".concat(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);var t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Et(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Et(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Et(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,i){var s=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;s._scene.camera.on("projMatrix",(function(){e=!0}));var t=$.mat4();return function(){return e&&$.inverseMat4(o.camera.projMatrix,t),t}}());var r=this._scene.canvas.gl,n=this._program,o=this._scene,a=r.drawingBufferWidth,l=r.drawingBufferHeight,u=o.camera.project._state,A=u.near,c=u.far;r.viewport(0,0,a,l),r.clearColor(0,0,0,1),r.enable(r.DEPTH_TEST),r.disable(r.BLEND),r.frontFace(r.CCW),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),n.bind(),Nt[0]=a,Nt[1]=l,r.uniform2fv(this._uViewport,Nt),r.uniform1f(this._uCameraNear,A),r.uniform1f(this._uCameraFar,c),r.uniform1f(this._uDepthCutoff,.01),0===i?r.uniform2fv(this._uSampleOffsets,Ut):r.uniform2fv(this._uSampleOffsets,Lt),r.uniform1fv(this._uSampleWeights,Ot);var h=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,h,0),n.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),r.drawElements(r.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Ht(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Vt(e,t){for(var i=[],s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}var jt=function(){function e(t,i,s){w(this,e),s=s||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}return C(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){if(this._touch.apply(this,arguments),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"createTexture",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}},{key:"_touch",value:function(){var e,t,i=this,s=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=s.drawingBufferWidth,t=s.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;this.buffer.textures.forEach((function(e){return s.deleteTexture(e)})),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}for(var r,n=[],o=arguments.length,a=new Array(o),l=0;l0?n.push.apply(n,A(a.map((function(s){return i.createTexture(e,t,s)})))):n.push(this.createTexture(e,t)),this._hasDepthTexture&&(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,e,t,0,s.DEPTH_COMPONENT,s.FLOAT,null));var u=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,u),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,e,t);var c=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,c);for(var h=0;h0&&s.drawBuffers(n.map((function(e,t){return s.COLOR_ATTACHMENT0+t}))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,r,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,u),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,c),!s.isFramebuffer(c))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);var d=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(d){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+d}this.buffer={framebuf:c,renderbuf:u,texture:n[0],textures:n,depthTexture:r,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,u=new r(n),A=this.gl;return A.readBuffer(A.COLOR_ATTACHMENT0+o),A.readPixels(a,l,1,1,i||A.RGBA,s||A.UNSIGNED_BYTE,u,0),u}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,n=new i(this.buffer.width*this.buffer.height*s),o=this.gl;return o.readBuffer(o.COLOR_ATTACHMENT0+r),o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,n,0),n}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,n=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=this.buffer.width,a=this.buffer.height,l=a/2|0,u=4*o,A=new Uint8Array(4*o),c=0;c0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,i=this.buffer.width,s=this.buffer.height,r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){var n=document.createElement("canvas"),o=n.getContext("2d");n.width=i,n.height=s,r={pixelData:new e(i*s*t),canvas:n,context:o,imageData:o.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var 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))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;this.buffer.textures.forEach((function(t){return e.deleteTexture(t)})),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),Gt=function(){function e(t){w(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return C(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,s=i[e];return s||(s=new jt(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}();function zt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}var Kt=function(e,t){t=t||{};var i=new gt(e),s=e.canvas.canvas,r=e.canvas.gl,n=!!t.transparent,o=t.alphaDepthMask,a=new Q({}),l={},u={},A=!0,c=!0,h=!0,d=!0,p=!0,f=!0,v=!0,g=!0,m=new Gt(e),_=!1,y=new Rt(e),b=new Qt(e);function B(){A&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],i=t.drawableMap,s=t.drawableListPreCull,r=0;for(var n in i)i.hasOwnProperty(n)&&(s[r++]=i[n]);s.length=r}}(),A=!1,c=!0),c&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),c=!1,h=!0),h&&function(){for(var e in l)if(l.hasOwnProperty(e)){for(var t=l[e],i=t.drawableListPreCull,s=t.drawableList,r=0,n=0,o=i.length;n0)for(i.withSAO=!0,I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||G>0||N>0||Q>0){if(r.enable(r.CULL_FACE),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):(r.blendEquation(r.FUNC_ADD),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,o||r.depthMask(!1),(N>0||Q>0)&&r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),Q>0)for(I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||K>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),K>0)for(I=0;I0)for(I=0;I0||X>0||z>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),r.enable(r.CULL_FACE),X>0)for(I=0;I0)for(I=0;I0||Y>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),Y>0)for(I=0;I0)for(I=0;I0||q>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),q>0)for(I=0;I0)for(I=0;I1&&void 0!==arguments[1]?arguments[1]:o;p.reset(),B();var f=null,v=null;for(var g in p.pickSurface=h.pickSurface,h.canvasPos?(u[0]=h.canvasPos[0],u[1]=h.canvasPos[1],f=e.camera.viewMatrix,v=e.camera.projMatrix,p.canvasPos=h.canvasPos):(h.matrix?(f=h.matrix,v=e.camera.projMatrix):(A.set(h.origin||[0,0,0]),c.set(h.direction||[0,0,1]),d=$.addVec3(A,c,t),r[0]=Math.random(),r[1]=Math.random(),r[2]=Math.random(),$.normalizeVec3(r),$.cross3Vec3(c,r,n),f=$.lookAtMat4v(A,d,n,i),v=e.camera.ortho.matrix,p.origin=A,p.direction=c),u[0]=.5*s.clientWidth,u[1]=.5*s.clientHeight),l)if(l.hasOwnProperty(g))for(var _=l[g].drawableList,y=0,b=_.length;y4&&void 0!==arguments[4]?arguments[4]:C;if(!n&&!o)return this.pick({canvasPos:t,pickSurface:!0});var A=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickZNear=e.camera.project.near,i.pickZFar=e.camera.project.far,s=s||30;var c=m.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*s+1,2*s+1]});i.snapVectorA=[k(t[0]*A,r.drawingBufferWidth),I(t[1]*A,r.drawingBufferHeight)],i.snapInvVectorAB=[r.drawingBufferWidth/(2*s),r.drawingBufferHeight/(2*s)],c.bind(r.RGBA32I,r.RGBA32I,r.RGBA8UI),r.viewport(0,0,c.size[0],c.size[1]),r.enable(r.DEPTH_TEST),r.frontFace(r.CCW),r.disable(r.CULL_FACE),r.depthMask(!0),r.disable(r.BLEND),r.depthFunc(r.LEQUAL),r.clear(r.DEPTH_BUFFER_BIT),r.clearBufferiv(r.COLOR,0,new Int32Array([0,0,0,0])),r.clearBufferiv(r.COLOR,1,new Int32Array([0,0,0,0])),r.clearBufferuiv(r.COLOR,2,new Uint32Array([0,0,0,0]));var h=e.camera.viewMatrix,d=e.camera.projMatrix;for(var p in l)if(l.hasOwnProperty(p))for(var f=l[p].drawableList,v=0,g=f.length;v0){var j=Math.floor(V/4),G=c.size[0],z=j%G-Math.floor(G/2),K=Math.floor(j/G)-Math.floor(G/2),W=Math.sqrt(Math.pow(z,2)+Math.pow(K,2));H.push({x:z,y:K,dist:W,isVertex:n&&o?B[V+3]>b.length/2:n,result:[B[V+0],B[V+1],B[V+2],B[V+3]],normal:[x[V+0],x[V+1],x[V+2],x[V+3]],id:[w[V+0],w[V+1],w[V+2],w[V+3]]})}var X=null,J=null,Y=null,Z=null;if(H.length>0){H.sort((function(e,t){return e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist})),Z=H[0].isVertex?"vertex":"edge";var q=H[0].result,ee=H[0].normal,te=H[0].id,ie=b[q[3]],se=ie.origin,re=ie.coordinateScale;J=$.normalizeVec3([ee[0]/$.MAX_INT,ee[1]/$.MAX_INT,ee[2]/$.MAX_INT]),X=[q[0]*re[0]+se[0],q[1]*re[1]+se[1],q[2]*re[2]+se[2]],Y=a.items[te[0]+(te[1]<<8)+(te[2]<<16)+(te[3]<<24)]}if(null===P&&null==X)return null;var ne=null;null!==X&&(ne=e.camera.projectWorldPos(X));var oe=Y&&Y.delegatePickedEntity?Y.delegatePickedEntity():Y;return u.reset(),u.snappedToEdge="edge"===Z,u.snappedToVertex="vertex"===Z,u.worldPos=X,u.worldNormal=J,u.entity=oe,u.canvasPos=t,u.snappedCanvasPos=ne||t,u}),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new St(e,m),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){for(var e in B(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e))for(var t=l[e].drawableList,s=0,n=t.length;s0&&void 0!==arguments[0]?arguments[0]:{},t=m.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),_=!0},this.renderSnapshot=function(){_&&(m.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),h=!0)},this.readSnapshot=function(e){return m.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return m.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){_&&(m.getRenderBuffer("snapshot").unbind(),_=!1)},this.destroy=function(){l={},u={},m.destroy(),y.destroy(),b.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Wt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).KEY_BACKSPACE=8,s.KEY_TAB=9,s.KEY_ENTER=13,s.KEY_SHIFT=16,s.KEY_CTRL=17,s.KEY_ALT=18,s.KEY_PAUSE_BREAK=19,s.KEY_CAPS_LOCK=20,s.KEY_ESCAPE=27,s.KEY_PAGE_UP=33,s.KEY_PAGE_DOWN=34,s.KEY_END=35,s.KEY_HOME=36,s.KEY_LEFT_ARROW=37,s.KEY_UP_ARROW=38,s.KEY_RIGHT_ARROW=39,s.KEY_DOWN_ARROW=40,s.KEY_INSERT=45,s.KEY_DELETE=46,s.KEY_NUM_0=48,s.KEY_NUM_1=49,s.KEY_NUM_2=50,s.KEY_NUM_3=51,s.KEY_NUM_4=52,s.KEY_NUM_5=53,s.KEY_NUM_6=54,s.KEY_NUM_7=55,s.KEY_NUM_8=56,s.KEY_NUM_9=57,s.KEY_A=65,s.KEY_B=66,s.KEY_C=67,s.KEY_D=68,s.KEY_E=69,s.KEY_F=70,s.KEY_G=71,s.KEY_H=72,s.KEY_I=73,s.KEY_J=74,s.KEY_K=75,s.KEY_L=76,s.KEY_M=77,s.KEY_N=78,s.KEY_O=79,s.KEY_P=80,s.KEY_Q=81,s.KEY_R=82,s.KEY_S=83,s.KEY_T=84,s.KEY_U=85,s.KEY_V=86,s.KEY_W=87,s.KEY_X=88,s.KEY_Y=89,s.KEY_Z=90,s.KEY_LEFT_WINDOW=91,s.KEY_RIGHT_WINDOW=92,s.KEY_SELECT_KEY=93,s.KEY_NUMPAD_0=96,s.KEY_NUMPAD_1=97,s.KEY_NUMPAD_2=98,s.KEY_NUMPAD_3=99,s.KEY_NUMPAD_4=100,s.KEY_NUMPAD_5=101,s.KEY_NUMPAD_6=102,s.KEY_NUMPAD_7=103,s.KEY_NUMPAD_8=104,s.KEY_NUMPAD_9=105,s.KEY_MULTIPLY=106,s.KEY_ADD=107,s.KEY_SUBTRACT=109,s.KEY_DECIMAL_POINT=110,s.KEY_DIVIDE=111,s.KEY_F1=112,s.KEY_F2=113,s.KEY_F3=114,s.KEY_F4=115,s.KEY_F5=116,s.KEY_F6=117,s.KEY_F7=118,s.KEY_F8=119,s.KEY_F9=120,s.KEY_F10=121,s.KEY_F11=122,s.KEY_F12=123,s.KEY_NUM_LOCK=144,s.KEY_SCROLL_LOCK=145,s.KEY_SEMI_COLON=186,s.KEY_EQUAL_SIGN=187,s.KEY_COMMA=188,s.KEY_DASH=189,s.KEY_PERIOD=190,s.KEY_FORWARD_SLASH=191,s.KEY_GRAVE_ACCENT=192,s.KEY_OPEN_BRACKET=219,s.KEY_BACK_SLASH=220,s.KEY_CLOSE_BRACKET=221,s.KEY_SINGLE_QUOTE=222,s.KEY_SPACE=32,s.element=r.element,s.altDown=!1,s.ctrlDown=!1,s.mouseDownLeft=!1,s.mouseDownMiddle=!1,s.mouseDownRight=!1,s.keyDown=[],s.enabled=!0,s.keyboardEnabled=!0,s.mouseover=!1,s.mouseCanvasPos=$.vec2(),s._keyboardEventsElement=r.keyboardEventsElement||document,s._bindEvents(),s}return C(i,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}});var t=this.scene.tickify((function(){return e.fire("mousemove",e.mouseCanvasPos,!0)}));this.element.addEventListener("mousemove",this._mouseMoveListener=function(i){e.enabled&&(e._getMouseCanvasPos(i),t(),e.mouseover&&i.preventDefault())});var i=this.scene.tickify((function(t){e.fire("mousewheel",t,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=function(t,s){if(e.enabled){var r=Math.max(-1,Math.min(1,40*-t.deltaY));i(r)}},{passive:!0});var s,r;this.on("mousedown",(function(e){s=e[0],r=e[1]})),this.on("mouseup",(function(t){s>=t[0]-2&&s<=t[0]+2&&r>=t[1]-2&&r<=t[1]+2&&e.fire("mouseclicked",t,!0)})),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getMouseCanvasPos",value:function(e){if(e){for(var t=e.target,i=0,s=0;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._unbindEvents()}}]),i}(),Xt=new Q({}),Jt=function(){function e(t){for(var i in w(this,e),this.id=Xt.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return C(e,[{key:"destroy",value:function(){Xt.removeItem(this.id)}}]),e}(),Yt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({boundary:[0,0,100,100]}),s.boundary=r.boundary,s.autoBoundary=r.autoBoundary,s}return C(i,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Zt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s._fov=60,s._canvasResized=s.scene.canvas.on("boundary",s._needUpdate,b(s)),s.fov=r.fov,s.fovAxis=r.fovAxis,s.near=r.near,s.far=r.far,s}return C(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis,s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),$.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(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))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),qt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.scale=r.scale,s.near=r.near,s.far=r.far,s._onCanvasBoundary=s.scene.canvas.on("boundary",s._needUpdate,b(s)),s}return C(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,s,r=this.scene,n=.5*this._scale,o=r.canvas.boundary,a=o[2],l=o[3],u=a/l;a>l?(e=-n,t=n,i=n/u,s=-n/u):(e=-n*u,t=n*u,i=n,s=-n),$.orthoMat4c(e,t,s,i,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),$t=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._left=-1,s._right=1,s._bottom=-1,s._top=1,s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.left=r.left,s.right=r.right,s.bottom=r.bottom,s.top=r.top,s.near=r.near,s.far=r.far,s}return C(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){$.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)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),ei=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4()}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!1,s.matrix=r.matrix,s}return C(i,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(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)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),ti=$.vec3(),ii=$.vec3(),si=$.vec3(),ri=$.vec3(),ni=$.vec3(),oi=$.vec3(),ai=$.vec4(),li=$.vec4(),ui=$.vec4(),Ai=$.mat4(),ci=$.mat4(),hi=$.vec3(),di=$.vec3(),pi=$.vec3(),fi=$.vec3(),vi=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({deviceMatrix:$.mat4(),hasDeviceMatrix:!1,matrix:$.mat4(),normalMatrix:$.mat4(),inverseMatrix:$.mat4()}),s._perspective=new Zt(b(s)),s._ortho=new qt(b(s)),s._frustum=new $t(b(s)),s._customProjection=new ei(b(s)),s._project=s._perspective,s._eye=$.vec3([0,0,10]),s._look=$.vec3([0,0,0]),s._up=$.vec3([0,1,0]),s._worldUp=$.vec3([0,1,0]),s._worldRight=$.vec3([1,0,0]),s._worldForward=$.vec3([0,0,-1]),s.deviceMatrix=r.deviceMatrix,s.eye=r.eye,s.look=r.look,s.up=r.up,s.worldAxis=r.worldAxis,s.gimbalLock=r.gimbalLock,s.constrainPitch=r.constrainPitch,s.projection=r.projection,s._perspective.on("matrix",(function(){"perspective"===s._projectionType&&s.fire("projMatrix",s._perspective.matrix)})),s._ortho.on("matrix",(function(){"ortho"===s._projectionType&&s.fire("projMatrix",s._ortho.matrix)})),s._frustum.on("matrix",(function(){"frustum"===s._projectionType&&s.fire("projMatrix",s._frustum.matrix)})),s._customProjection.on("matrix",(function(){"customProjection"===s._projectionType&&s.fire("projMatrix",s._customProjection.matrix)})),s}return C(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?($.subVec3(this._eye,this._look,hi),$.normalizeVec3(hi,di),$.mulVec3Scalar(di,1e3,pi),$.addVec3(this._look,pi,fi),e=fi):e=this._eye,t.hasDeviceMatrix?($.lookAtMat4v(e,this._look,this._up,ci),$.mulMat4(t.deviceMatrix,ci,t.matrix)):$.lookAtMat4v(e,this._look,this._up,t.matrix),$.inverseMat4(this._state.matrix,this._state.inverseMatrix),$.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=$.subVec3(this._eye,this._look,ti);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Ai),t=$.transformPoint3(Ai,t,ii),this.eye=$.addVec3(this._look,t,si),this.up=$.transformPoint3(Ai,this._up,ri)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._eye,this._look,ti),i=$.cross3Vec3($.normalizeVec3(t,ii),$.normalizeVec3(this._up,si));$.rotationMat4v(.0174532925*e,i,Ai),t=$.transformPoint3(Ai,t,ri),this.up=$.transformPoint3(Ai,this._up,ni),this.eye=$.addVec3(t,this._look,oi)}}},{key:"yaw",value:function(e){var t=$.subVec3(this._look,this._eye,ti);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Ai),t=$.transformPoint3(Ai,t,ii),this.look=$.addVec3(t,this._eye,si),this._gimbalLock&&(this.up=$.transformPoint3(Ai,this._up,ri))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._look,this._eye,ti),i=$.cross3Vec3($.normalizeVec3(t,ii),$.normalizeVec3(this._up,si));$.rotationMat4v(.0174532925*e,i,Ai),this.up=$.transformPoint3(Ai,this._up,oi),t=$.transformPoint3(Ai,t,ri),this.look=$.addVec3(t,this._eye,ni)}}},{key:"pan",value:function(e){var t,i=$.subVec3(this._eye,this._look,ti),s=[0,0,0];if(0!==e[0]){var r=$.cross3Vec3($.normalizeVec3(i,[]),$.normalizeVec3(this._up,ii));t=$.mulVec3Scalar(r,e[0]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]}0!==e[1]&&(t=$.mulVec3Scalar($.normalizeVec3(this._up,si),e[1]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),0!==e[2]&&(t=$.mulVec3Scalar($.normalizeVec3(i,ri),e[2]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),this.eye=$.addVec3(this._eye,s,ni),this.look=$.addVec3(this._look,s,oi)}},{key:"zoom",value:function(e){var t=$.subVec3(this._eye,this._look,ti),i=Math.abs($.lenVec3(t,ii)),s=Math.abs(i+e);if(!(s<.5)){var r=$.normalizeVec3(t,si);this.eye=$.addVec3(this._look,$.mulVec3Scalar(r,s),ri)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(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)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=$.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)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return $.lenVec3($.subVec3(this._look,this._eye,ti))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(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))}},{key:"project",get:function(){return this._project}},{key:"projectWorldPos",value:function(e){var t=ai,i=li,s=ui;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,$.mulMat4v4(this.viewMatrix,t,i),$.mulMat4v4(this.projMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;var r=this.scene.canvas.canvas,n=r.offsetWidth/2,o=r.offsetHeight/2;return[s[0]*n+n,s[1]*o+o]}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),gi=function(e){g(i,Be);var t=_(i);function i(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),t.call(this,e,s)}return C(i,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),i}(),mi=function(e){g(i,gi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._shadowRenderBuf=null,s._shadowViewMatrix=null,s._shadowProjMatrix=null,s._shadowViewMatrixDirty=!0,s._shadowProjMatrixDirty=!0;var n=s.scene.camera,o=s.scene.canvas;return s._onCameraViewMatrix=n.on("viewMatrix",(function(){s._shadowViewMatrixDirty=!0})),s._onCameraProjMatrix=n.on("projMatrix",(function(){s._shadowProjMatrixDirty=!0})),s._onCanvasBoundary=o.on("boundary",(function(){s._shadowProjMatrixDirty=!0})),s._state=new Jt({type:"dir",dir:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,space:r.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=$.identityMat4());var e=s.scene.camera,t=s._state.dir,i=e.look,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];$.lookAtMat4v(r,i,[0,1,0],s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:function(){return s._shadowProjMatrixDirty&&(s._shadowProjMatrix||(s._shadowProjMatrix=$.identityMat4()),$.orthoMat4c(-40,40,-40,40,-40,80,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1),s._shadowProjMatrix},getShadowRenderBuf:function(){return s._shadowRenderBuf||(s._shadowRenderBuf=new jt(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf}}),s.dir=r.dir,s.color=r.color,s.intensity=r.intensity,s.castsShadow=r.castsShadow,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}(),_i=function(e){g(i,gi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state={type:"ambient",color:$.vec3([.7,.7,.7]),intensity:1},s.color=r.color,s.intensity=r.intensity,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),i}(),yi=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),s=t.call(this,e,r),se.memory.meshes++,s}return C(i,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),se.memory.meshes--}}]),i}(),bi=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(r,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=r.length;AI)||(F=i[P.index1],E=i[P.index2],(!S&&F>65535||E>65535)&&(S=!0),k.push(F),k.push(E));return S?new Uint32Array(k):new Uint16Array(k)}}();var Bi=function(){var e=$.mat4(),t=$.mat4();return function(i,s){s=s||$.mat4();var r=i[0],n=i[1],o=i[2],a=i[3]-r,l=i[4]-n,u=i[5]-o,A=65535;return $.identityMat4(e),$.translationMat4v(i,e),$.identityMat4(t),$.scalingMat4v([a/A,l/A,u/A],t),$.mulMat4(e,t,s),s}}(),xi=function(){var e=$.mat4(),t=$.mat4();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);for(n=0;n=0?1:-1),a=(1-Math.abs(r))*(n>=0?1:-1);r=o,n=a}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function Ci(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Mi(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var Fi={getPositionsBounds:function(e){var t,i,s=new Float32Array(3),r=new Float32Array(3);for(t=0;t<3;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,s=new Float32Array(2),r=new Float32Array(2);for(t=0;t<2;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;sr&&(i=t,r=s),(s=Mi(e,o,Ci(t=Pi(e,o,"floor","ceil"))))>r&&(i=t,r=s),(s=Mi(e,o,Ci(t=Pi(e,o,"ceil","ceil"))))>r&&(i=t,r=s),n[o]=i[0],n[o+1]=i[1];return n},decompressNormals:function(e,t){for(var i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/l,t[s+1]=o/l,t[s+2]=a/l,s+=3}return t},decompressNormal:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},Ei=se.memory,ki=$.AABB3(),Ii=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._state=new Jt({compressGeometry:!!r.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),s._numTriangles=0,s._edgeThreshold=r.edgeThreshold||10,s._edgeIndicesBuf=null,s._pickTrianglePositionsBuf=null,s._pickTriangleColorsBuf=null,s._aabbDirty=!0,s._boundingSphere=!0,s._aabb=null,s._aabbDirty=!0,s._obb=null,s._obbDirty=!0;var n=s._state,o=s.scene.canvas.gl;switch(r.primitive=r.primitive||"triangles",r.primitive){case"points":n.primitive=o.POINTS,n.primitiveName=r.primitive;break;case"lines":n.primitive=o.LINES,n.primitiveName=r.primitive;break;case"line-loop":n.primitive=o.LINE_LOOP,n.primitiveName=r.primitive;break;case"line-strip":n.primitive=o.LINE_STRIP,n.primitiveName=r.primitive;break;case"triangles":n.primitive=o.TRIANGLES,n.primitiveName=r.primitive;break;case"triangle-strip":n.primitive=o.TRIANGLE_STRIP,n.primitiveName=r.primitive;break;case"triangle-fan":n.primitive=o.TRIANGLE_FAN,n.primitiveName=r.primitive;break;default:s.error("Unsupported value for 'primitive': '"+r.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),n.primitive=o.TRIANGLES,n.primitiveName=r.primitive}if(r.positions)if(s._state.compressGeometry){var a=Fi.getPositionsBounds(r.positions),l=Fi.compressPositions(r.positions,a.min,a.max);n.positions=l.quantized,n.positionsDecodeMatrix=l.decodeMatrix}else n.positions=r.positions.constructor===Float32Array?r.positions:new Float32Array(r.positions);if(r.colors&&(n.colors=r.colors.constructor===Float32Array?r.colors:new Float32Array(r.colors)),r.uv)if(s._state.compressGeometry){var u=Fi.getUVBounds(r.uv),A=Fi.compressUVs(r.uv,u.min,u.max);n.uv=A.quantized,n.uvDecodeMatrix=A.decodeMatrix}else n.uv=r.uv.constructor===Float32Array?r.uv:new Float32Array(r.uv);return r.normals&&(s._state.compressGeometry?n.normals=Fi.compressNormals(r.normals):n.normals=r.normals.constructor===Float32Array?r.normals:new Float32Array(r.normals)),r.indices&&(n.indices=r.indices.constructor===Uint32Array||r.indices.constructor===Uint16Array?r.indices:new Uint32Array(r.indices),"triangles"===s._state.primitiveName&&(s._numTriangles=r.indices.length/3)),s._buildHash(),Ei.meshes++,s._buildVBOs(),s}return C(i,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Ei.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Et(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Ei.positions+=e.positionsBuf.numItems),e.normals){var i=e.compressGeometry;e.normalsBuf=new Et(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Ei.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Et(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Ei.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Et(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Ei.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=bi(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Ei.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=$.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Et(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Et(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Ei.positions+=this._pickTrianglePositionsBuf.numItems,Ei.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Fi.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){var s=Fi.getPositionsBounds(e),r=Fi.compressPositions(e,s.min,s.max);e=r.quantized,t.positionsDecodeMatrix=r.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Fi.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Fi.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=$.AABB3()),$.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=$.OBB3()),$.positions3ToAABB3(this._state.positions,ki,this._state.positionsDecodeMatrix),$.AABB3ToOBB3(ki,this._obb),this._obbDirty=!1),this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Ei.meshes--}}]),i}();function Di(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);var r=e.center,n=r?r[0]:0,o=r?r[1]:0,a=r?r[2]:0,l=-t+n,u=-i+o,A=-s+a,c=t+n,h=i+o,d=s+a;return le.apply(e,{positions:[c,h,d,l,h,d,l,u,d,c,u,d,c,h,d,c,u,d,c,u,A,c,h,A,c,h,d,c,h,A,l,h,A,l,h,d,l,h,d,l,h,A,l,u,A,l,u,d,l,u,A,c,u,A,c,u,d,l,u,d,c,u,A,l,u,A,l,h,A,c,h,A],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}var Si=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),s=t.call(this,e,r),se.memory.materials++,s}return C(i,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),se.memory.materials--}}]),i}(),Ti={opaque:0,mask:1,blend:2},Ri=["opaque","mask","blend"],Li=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"PhongMaterial",ambient:$.vec3([1,1,1]),diffuse:$.vec3([1,1,1]),specular:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.ambient=r.ambient,s.diffuse=r.diffuse,s.specular=r.specular,s.emissive=r.emissive,s.alpha=r.alpha,s.shininess=r.shininess,s.reflectivity=r.reflectivity,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,r.ambientMap&&(s._ambientMap=s._checkComponent("Texture",r.ambientMap)),r.diffuseMap&&(s._diffuseMap=s._checkComponent("Texture",r.diffuseMap)),r.specularMap&&(s._specularMap=s._checkComponent("Texture",r.specularMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.reflectivityMap&&(s._reflectivityMap=s._checkComponent("Texture",r.reflectivityMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.diffuseFresnel&&(s._diffuseFresnel=s._checkComponent("Fresnel",r.diffuseFresnel)),r.specularFresnel&&(s._specularFresnel=s._checkComponent("Fresnel",r.specularFresnel)),r.emissiveFresnel&&(s._emissiveFresnel=s._checkComponent("Fresnel",r.emissiveFresnel)),r.alphaFresnel&&(s._alphaFresnel=s._checkComponent("Fresnel",r.alphaFresnel)),r.reflectivityFresnel&&(s._reflectivityFresnel=s._checkComponent("Fresnel",r.reflectivityFresnel)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return Ri[this._state.alphaMode]},set:function(e){var t=Ti[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ui={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},Oi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),s._preset="default",r.preset?(s.preset=r.preset,void 0!==r.fill&&(s.fill=r.fill),r.fillColor&&(s.fillColor=r.fillColor),void 0!==r.fillAlpha&&(s.fillAlpha=r.fillAlpha),void 0!==r.edges&&(s.edges=r.edges),r.edgeColor&&(s.edgeColor=r.edgeColor),void 0!==r.edgeAlpha&&(s.edgeAlpha=r.edgeAlpha),void 0!==r.edgeWidth&&(s.edgeWidth=r.edgeWidth),void 0!==r.backfaces&&(s.backfaces=r.backfaces),void 0!==r.glowThrough&&(s.glowThrough=r.glowThrough)):(s.fill=r.fill,s.fillColor=r.fillColor,s.fillAlpha=r.fillAlpha,s.edges=r.edges,s.edgeColor=r.edgeColor,s.edgeAlpha=r.edgeAlpha,s.edgeWidth=r.edgeWidth,s.backfaces=r.backfaces,s.glowThrough=r.glowThrough),s}return C(i,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return Ui}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ui[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ui).join(", "))}}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ni={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},Qi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),s._preset="default",r.preset?(s.preset=r.preset,r.edgeColor&&(s.edgeColor=r.edgeColor),void 0!==r.edgeAlpha&&(s.edgeAlpha=r.edgeAlpha),void 0!==r.edgeWidth&&(s.edgeWidth=r.edgeWidth)):(s.edgeColor=r.edgeColor,s.edgeAlpha=r.edgeAlpha,s.edgeWidth=r.edgeWidth),s.edges=!1!==r.edges,s}return C(i,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return Ni}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ni[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ni).join(", "))}}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Hi={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},Vi=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._units="meters",s._scale=1,s._origin=$.vec3([0,0,0]),s.units=r.units,s.scale=r.scale,s.origin=r.origin,s}return C(i,[{key:"unitsInfo",get:function(){return Hi}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),Hi[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),i}(),ji=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._supported=mt.SUPPORTED_EXTENSIONS.OES_standard_derivatives,s.enabled=r.enabled,s.kernelRadius=r.kernelRadius,s.intensity=r.intensity,s.bias=r.bias,s.scale=r.scale,s.minResolution=r.minResolution,s.numSamples=r.numSamples,s.blur=r.blur,s.blendCutoff=r.blendCutoff,s.blendFactor=r.blendFactor,s}return C(i,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this)}}]),i}(),Gi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},zi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),r.preset?(s.preset=r.preset,void 0!==r.pointSize&&(s.pointSize=r.pointSize),void 0!==r.roundPoints&&(s.roundPoints=r.roundPoints),void 0!==r.perspectivePoints&&(s.perspectivePoints=r.perspectivePoints),void 0!==r.minPerspectivePointSize&&(s.minPerspectivePointSize=r.minPerspectivePointSize),void 0!==r.maxPerspectivePointSize&&(s.maxPerspectivePointSize=r.minPerspectivePointSize)):(s._preset="default",s.pointSize=r.pointSize,s.roundPoints=r.roundPoints,s.perspectivePoints=r.perspectivePoints,s.minPerspectivePointSize=r.minPerspectivePointSize,s.maxPerspectivePointSize=r.maxPerspectivePointSize),s.filterIntensity=r.filterIntensity,s.minIntensity=r.minIntensity,s.maxIntensity=r.maxIntensity,s}return C(i,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return Gi}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Gi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Gi).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ki={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},Wi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"LinesMaterial",lineWidth:null}),r.preset?(s.preset=r.preset,void 0!==r.lineWidth&&(s.lineWidth=r.lineWidth)):(s._preset="default",s.lineWidth=r.lineWidth),s}return C(i,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Ki}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ki[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ki).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function Xi(e,t){for(var i,s,r={},n=0,o=t.length;n1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),s=t.call(this,null,r);var n=r.canvasElement||document.getElementById(r.canvasId);if(!(n instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";s._tickifiedFunctions={};var o=!!r.transparent,a=!!r.alphaDepthMask;return s._aabbDirty=!0,s.viewer=e,s.occlusionTestCountdown=0,s.loading=0,s.startTime=(new Date).getTime(),s.models={},s.objects={},s._numObjects=0,s.visibleObjects={},s._numVisibleObjects=0,s.xrayedObjects={},s._numXRayedObjects=0,s.highlightedObjects={},s._numHighlightedObjects=0,s.selectedObjects={},s._numSelectedObjects=0,s.colorizedObjects={},s._numColorizedObjects=0,s.opacityObjects={},s._numOpacityObjects=0,s.offsetObjects={},s._numOffsetObjects=0,s._modelIds=null,s._objectIds=null,s._visibleObjectIds=null,s._xrayedObjectIds=null,s._highlightedObjectIds=null,s._selectedObjectIds=null,s._colorizedObjectIds=null,s._opacityObjectIds=null,s._offsetObjectIds=null,s._collidables={},s._compilables={},s._needRecompile=!1,s.types={},s.components={},s.sectionPlanes={},s.lights={},s.lightMaps={},s.reflectionMaps={},s.bitmaps={},s.lineSets={},s.realWorldOffset=r.realWorldOffset||new Float64Array([0,0,0]),s.canvas=new vt(b(s),{dontClear:!0,canvas:n,spinnerElementId:r.spinnerElementId,transparent:o,webgl2:!1!==r.webgl2,contextAttr:r.contextAttr||{},backgroundColor:r.backgroundColor,backgroundColorFromAmbientLight:r.backgroundColorFromAmbientLight,premultipliedAlpha:r.premultipliedAlpha}),s.canvas.on("boundary",(function(){s.glRedraw()})),s.canvas.on("webglContextFailed",(function(){alert("xeokit failed to find WebGL!")})),s._renderer=new Kt(b(s),{transparent:o,alphaDepthMask:a}),s._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;var e=null;this.getHash=function(){if(e)return e;var t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";for(var i=[],s=0,r=t;sthis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},s._sectionPlanesState.setNumCachedSectionPlanes(r.numCachedSectionPlanes||0),s._lightsState=new function(){var e=$.vec4([0,0,0,0]),t=$.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];var i=null,s=null;this.getHash=function(){if(i)return i;for(var e,t=[],s=this.lights,r=0,n=s.length;r0&&t.push("/lm"),this.reflectionMaps.length>0&&t.push("/rm"),t.push(";"),i=t.join("")},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(var t=0,r=this.lights.length;t1&&void 0!==arguments[1])||arguments[1];e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}},{key:"_deRegisterVisibleObject",value:function(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}},{key:"_objectXRayedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}},{key:"_deRegisterXRayedObject",value:function(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}},{key:"_objectHighlightedUpdated",value:function(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}},{key:"_deRegisterHighlightedObject",value:function(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}},{key:"_objectSelectedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}},{key:"_deRegisterSelectedObject",value:function(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}},{key:"_objectColorizeUpdated",value:function(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}},{key:"_deRegisterColorizedObject",value:function(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}},{key:"_objectOpacityUpdated",value:function(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}},{key:"_deRegisterOpacityObject",value:function(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}},{key:"_objectOffsetUpdated",value:function(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}},{key:"_deRegisterOffsetObject",value:function(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}},{key:"_webglContextLost",value:function(){for(var e in this.canvas.spinner.processes++,this.components)if(this.components.hasOwnProperty(e)){var t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}},{key:"_webglContextRestored",value:function(){var e=this.canvas.gl;for(var t in this.components)if(this.components.hasOwnProperty(t)){var i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}},{key:"capabilities",get:function(){return this._renderer.capabilities}},{key:"entityOffsetsEnabled",get:function(){return this._entityOffsetsEnabled}},{key:"pickSurfacePrecisionEnabled",get:function(){return!1}},{key:"logarithmicDepthBufferEnabled",get:function(){return this._logarithmicDepthBufferEnabled}},{key:"numCachedSectionPlanes",get:function(){return this._sectionPlanesState.getNumCachedSectionPlanes()},set:function(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}},{key:"pbrEnabled",get:function(){return this._pbrEnabled},set:function(e){this._pbrEnabled=!!e,this.glRedraw()}},{key:"dtxEnabled",get:function(){return this._dtxEnabled},set:function(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled},set:function(e){this._colorTextureEnabled=!!e,this.glRedraw()}},{key:"doOcclusionTest",value:function(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}},{key:"render",value:function(e){e&&_e.runTasks();var t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;var i,s,r=this._passes,n=this._clearEachPass;for(i=0;in&&(n=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),u=!0}u||(i=-100,s=-100,r=-100,n=100,o=100,a=100),this._aabb[0]=i,this._aabb[1]=s,this._aabb[2]=r,this._aabb[3]=n,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}},{key:"_setAABBDirty",value:function(){this._aabbDirty=!0,this.fire("boundary")}},{key:"pick",value:function(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");var i=e.includeEntities||e.include;i&&(e.includeEntityIds=Xi(this,i));var s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=Xi(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}},{key:"snapPick",value:function(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}},{key:"clear",value:function(){var e;for(var t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}},{key:"clearLights",value:function(){for(var e=Object.keys(this.lights),t=0,i=e.length;to&&(o=t[3]),t[4]>a&&(a=t[4]),t[5]>l&&(l=t[5]),i=!0}})),i){var u=$.AABB3();return u[0]=s,u[1]=r,u[2]=n,u[3]=o,u[4]=a,u[5]=l,u}return this.aabb}},{key:"setObjectsVisible",value:function(e,t){return this.withObjects(e,(function(e){var i=e.visible!==t;return e.visible=t,i}))}},{key:"setObjectsCollidable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.collidable!==t;return e.collidable=t,i}))}},{key:"setObjectsCulled",value:function(e,t){return this.withObjects(e,(function(e){var i=e.culled!==t;return e.culled=t,i}))}},{key:"setObjectsSelected",value:function(e,t){return this.withObjects(e,(function(e){var i=e.selected!==t;return e.selected=t,i}))}},{key:"setObjectsHighlighted",value:function(e,t){return this.withObjects(e,(function(e){var i=e.highlighted!==t;return e.highlighted=t,i}))}},{key:"setObjectsXRayed",value:function(e,t){return this.withObjects(e,(function(e){var i=e.xrayed!==t;return e.xrayed=t,i}))}},{key:"setObjectsEdges",value:function(e,t){return this.withObjects(e,(function(e){var i=e.edges!==t;return e.edges=t,i}))}},{key:"setObjectsColorized",value:function(e,t){return this.withObjects(e,(function(e){e.colorize=t}))}},{key:"setObjectsOpacity",value:function(e,t){return this.withObjects(e,(function(e){var i=e.opacity!==t;return e.opacity=t,i}))}},{key:"setObjectsPickable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.pickable!==t;return e.pickable=t,i}))}},{key:"setObjectsOffset",value:function(e,t){this.withObjects(e,(function(e){e.offset=t}))}},{key:"withObjects",value:function(e,t){le.isString(e)&&(e=[e]);for(var i=!1,s=0,r=e.length;ss&&(s=r,e.apply(void 0,A(i)))}));return this._tickifiedFunctions[t]={tickSubId:o,wrapperFunc:n},n}},{key:"destroy",value:function(){for(var e in f(B(i.prototype),"destroy",this).call(this),this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}]),i}(),Yi=1e3,Zi=1001,qi=1002,$i=1003,es=1004,ts=1004,is=1005,ss=1005,rs=1006,ns=1007,os=1007,as=1008,ls=1008,us=1009,As=1010,cs=1011,hs=1012,ds=1013,ps=1014,fs=1015,vs=1016,gs=1017,ms=1018,_s=1020,ys=1021,bs=1022,Bs=1023,xs=1024,ws=1025,Ps=1026,Cs=1027,Ms=1028,Fs=1029,Es=1030,ks=1031,Is=1033,Ds=33776,Ss=33777,Ts=33778,Rs=33779,Ls=35840,Us=35841,Os=35842,Ns=35843,Qs=36196,Hs=37492,Vs=37496,js=37808,Gs=37809,zs=37810,Ks=37811,Ws=37812,Xs=37813,Js=37814,Ys=37815,Zs=37816,qs=37817,$s=37818,er=37819,tr=37820,ir=37821,sr=36492,rr=3e3,nr=3001,or=1e4,ar=10001,lr=10002,ur=10003,Ar=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){var t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,n=e._state.billboard,o=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,u=[];u.push("#version 300 es"),u.push("// Lambertian drawing vertex shader"),u.push("in vec3 position;"),u.push("uniform mat4 modelMatrix;"),u.push("uniform mat4 viewMatrix;"),u.push("uniform mat4 projMatrix;"),u.push("uniform vec4 colorize;"),u.push("uniform vec3 offset;"),l&&u.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(u.push("uniform float logDepthBufFC;"),u.push("out float vFragDepth;"),u.push("bool isPerspectiveMatrix(mat4 m) {"),u.push(" return (m[2][3] == - 1.0);"),u.push("}"),u.push("out float isPerspective;"));a&&u.push("out vec4 vWorldPosition;");if(u.push("uniform vec4 lightAmbient;"),u.push("uniform vec4 materialColor;"),u.push("uniform vec3 materialEmissive;"),r.normalsBuf){u.push("in vec3 normal;"),u.push("uniform mat4 modelNormalMatrix;"),u.push("uniform mat4 viewNormalMatrix;");for(var A=0,c=s.lights.length;A= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),u.push(" }"),u.push(" return normalize(v);"),u.push("}"))}u.push("out vec4 vColor;"),"points"===r.primitiveName&&u.push("uniform float pointSize;");"spherical"!==n&&"cylindrical"!==n||(u.push("void billboard(inout mat4 mat) {"),u.push(" mat[0][0] = 1.0;"),u.push(" mat[0][1] = 0.0;"),u.push(" mat[0][2] = 0.0;"),"spherical"===n&&(u.push(" mat[1][0] = 0.0;"),u.push(" mat[1][1] = 1.0;"),u.push(" mat[1][2] = 0.0;")),u.push(" mat[2][0] = 0.0;"),u.push(" mat[2][1] = 0.0;"),u.push(" mat[2][2] =1.0;"),u.push("}"));u.push("void main(void) {"),u.push("vec4 localPosition = vec4(position, 1.0); "),u.push("vec4 worldPosition;"),l&&u.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?u.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):u.push("vec4 localNormal = vec4(normal, 0.0); "),u.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),u.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));u.push("mat4 viewMatrix2 = viewMatrix;"),u.push("mat4 modelMatrix2 = modelMatrix;"),o&&u.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(u.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),u.push("billboard(modelMatrix2);"),u.push("billboard(viewMatrix2);"),u.push("billboard(modelViewMatrix);"),r.normalsBuf&&(u.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),u.push("billboard(modelNormalMatrix2);"),u.push("billboard(viewNormalMatrix2);"),u.push("billboard(modelViewNormalMatrix);")),u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&u.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(u.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),u.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),u.push("float lambertian = 1.0;"),r.normalsBuf)for(var d=0,p=s.lights.length;d0,n=t.gammaOutput,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(var a=0,l=i.getNumAllocatedSectionPlanes();a 0.0) { discard; }"),o.push("}")}"points"===s.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)):(this.vertex=function(e){var t=e.scene;e._material;var i,s=e._state,r=t._sectionPlanesState,n=e._geometry._state,o=t._lightsState,a=s.billboard,l=s.background,u=s.stationary,A=function(e){if(!e._geometry._state.uvBuf)return!1;var t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=dr(e),h=r.getNumAllocatedSectionPlanes()>0,d=hr(e),p=!!n.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),h&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(var v=0,g=o.lights.length;v= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}A&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));n.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===n.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var m=0,_=o.lights.length;m<_;m++)o.lights[m].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+m+";"),f.push("uniform mat4 shadowProjMatrix"+m+";"),f.push("out vec4 vShadowPosFromLight"+m+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");c&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),u?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),c&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(c){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(var y=0,b=o.lights.length;y0,l=dr(e),u=s.uvBuf,A="PhongMaterial"===o.type,c="MetallicMaterial"===o.type,h="SpecularMaterial"===o.type,d=hr(e);t.gammaInput;var p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var v=0;v0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),n.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),A&&((n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = "+cr[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||h)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),n.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+cr[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(n.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));o.ambient&&f.push("uniform vec3 materialAmbient;");o.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==o.alpha&&null!==o.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");o.emissive&&f.push("uniform vec3 materialEmissive;");o.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==o.glossiness&&null!==o.glossiness&&f.push("uniform float materialGlossiness;");void 0!==o.shininess&&null!==o.shininess&&f.push("uniform float materialShininess;");o.specular&&f.push("uniform vec3 materialSpecular;");void 0!==o.metallic&&null!==o.metallic&&f.push("uniform float materialMetallic;");void 0!==o.roughness&&null!==o.roughness&&f.push("uniform float materialRoughness;");void 0!==o.specularF0&&null!==o.specularF0&&f.push("uniform float materialSpecularF0;");u&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));u&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));u&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));u&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&u&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&u&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&u&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));u&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));u&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&u&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&u&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&u&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(var g=0,m=n.lights.length;g 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),o.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");o.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):o.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");o.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");o.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==o.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==o.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==o.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==o.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==o.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));u&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+cr[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));u&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+cr[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));u&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+cr[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));u&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+cr[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));u&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));u&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(n.lights.length>0||n.lightMaps.length>0||n.reflectionMaps.length>0)){u&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),u&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),u&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),u&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),u&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),u&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),u&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),A&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),h&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),n.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),A&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(h||c)&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(var B=0,x=n.lights.length;B0)for(var f=s._sectionPlanesState.sectionPlanes,v=t.renderFlags,g=0;g0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(A=0,c=n.sectionPlanes.length;A0&&n.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,n.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),n.reflectionMaps.length>0&&n.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,n.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),this._uGammaFactor&&r.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};var mr=C((function e(t){w(this,e),this.vertex=function(e){var t=e.scene,i=t._lightsState,s=function(e){var t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,n=!!e._geometry._state.compressGeometry,o=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),n&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(var u=0,A=i.lights.length;u= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===o||"cylindrical"===o)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===o&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),n&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(n?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(var h=0,d=i.lights.length;h0,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));s&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}"points"===e._geometry._state.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var _r=new Q({}),yr=$.vec3(),br=function(e,t){this.id=_r.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new mr(t),this._allocate(t)},Br={};br.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Br[t];return i||(i=new br(t,e),Br[t]=i,se.memory.programs++),i._useCount++,i},br.prototype.put=function(){0==--this._useCount&&(_r.removeItem(this.id),this._program&&this._program.destroy(),delete Br[this._hash],se.memory.programs--)},br.prototype.webglContextRestored=function(){this._program=null},br.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var s=this._scene,r=s.camera,n=s.canvas.gl,o=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(a.originHash,u):r.viewMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){var A=s._sectionPlanesState.getNumAllocatedSectionPlanes(),c=s._sectionPlanesState.sectionPlanes.length;if(A>0)for(var h=s._sectionPlanesState.sectionPlanes,d=t.renderFlags,p=0;p0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Edges drawing vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));o.push("vColor = edgeColor;"),i&&o.push("vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));s&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var wr=new Q({}),Pr=$.vec3(),Cr=function(e,t){this.id=wr.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new xr(t),this._allocate(t)},Mr={};Cr.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Mr[t];return i||(i=new Cr(t,e),Mr[t]=i,se.memory.programs++),i._useCount++,i},Cr.prototype.put=function(){0==--this._useCount&&(wr.removeItem(this.id),this._program&&this._program.destroy(),delete Mr[this._hash],se.memory.programs--)},Cr.prototype.webglContextRestored=function(){this._program=null},Cr.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var s,r,n=this._scene,o=n.camera,a=n.canvas.gl,l=t._state,u=t._geometry,A=u._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):o.viewMatrix),l.clippable){var h=n._sectionPlanesState.getNumAllocatedSectionPlanes(),d=n._sectionPlanesState.sectionPlanes.length;if(h>0)for(var p=n._sectionPlanesState.sectionPlanes,f=t.renderFlags,v=0;v0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh picking vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("out vec4 vViewPosition;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("uniform vec2 pickClipPos;"),o.push("vec4 remapClipPos(vec4 clipPos) {"),o.push(" clipPos.xy /= clipPos.w;"),o.push(" clipPos.xy -= pickClipPos;"),o.push(" clipPos.xy *= clipPos.w;"),o.push(" return clipPos;"),o.push("}"),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"));o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = remapClipPos(clipPos);"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(t)}));var Er=$.vec3(),kr=function(e,t){this._hash=e,this._shaderSource=new Fr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ir={};kr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),i=Ir[t];if(!i){if((i=new kr(t,e)).errors)return console.log(i.errors.join("\n")),null;Ir[t]=i,se.memory.programs++}return i._useCount++,i},kr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ir[this._hash],se.memory.programs--)},kr.prototype.webglContextRestored=function(){this._program=null},kr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._state,n=t._material._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){var l=i._sectionPlanesState.getNumAllocatedSectionPlanes(),u=i._sectionPlanesState.sectionPlanes.length;if(l>0)for(var A=i._sectionPlanesState.sectionPlanes,c=t.renderFlags,h=0;h>24&255,b=_>>16&255,B=_>>8&255,x=255&_;s.uniform4f(this._uPickColor,x/255,B/255,b/255,y/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),o.indicesBuf?(s.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&s.drawArrays(s.TRIANGLES,0,o.positions.numItems)},kr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Ft(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=t._sectionPlanesState.sectionPlanes.length;r0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(t)}));var Sr=$.vec3(),Tr=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Dr(t),this._allocate(t)},Rr={};Tr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Rr[t];if(!i){if((i=new Tr(t,e)).errors)return console.log(i.errors.join("\n")),null;Rr[t]=i,se.memory.programs++}return i._useCount++,i},Tr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Rr[this._hash],se.memory.programs--)},Tr.prototype.webglContextRestored=function(){this._program=null},Tr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._state,n=t._material._state,o=t._geometry,a=t._geometry._state,l=t.origin,u=n.backfaces,A=n.frontface,c=i.camera.project,h=o._getPickTrianglePositions(),d=o._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){var p=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){var f=i._sectionPlanesState.getNumAllocatedSectionPlanes(),v=i._sectionPlanesState.sectionPlanes.length;if(f>0)for(var g=i._sectionPlanesState.sectionPlanes,m=t.renderFlags,_=0;_0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh occlusion vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(t)}));var Ur=$.vec3(),Or=function(e,t){this._hash=e,this._shaderSource=new Lr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Nr={};Or.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";"),i=Nr[t];if(!i){if((i=new Or(t,e)).errors)return console.log(i.errors.join("\n")),null;Nr[t]=i,se.memory.programs++}return i._useCount++,i},Or.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Nr[this._hash],se.memory.programs--)},Or.prototype.webglContextRestored=function(){this._program=null},Or.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._material._state,n=t._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){var l=r.backfaces;e.backfaces!==l&&(l?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=l);var u=r.frontface;e.frontface!==u&&(u?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=u),this._lastMaterialId=r.id}var A=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(n.originHash,a):A.viewMatrix),n.clippable){var c=i._sectionPlanesState.getNumAllocatedSectionPlanes(),h=i._sectionPlanesState.sectionPlanes.length;if(c>0)for(var d=i._sectionPlanesState.sectionPlanes,p=t.renderFlags,f=0;f0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(t),this.fragment=function(e){var t=e.scene;t.canvas.gl;var i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(t)}));var Hr=function(e,t){this._hash=e,this._shaderSource=new Qr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Vr={};Hr.get=function(e){var t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),s=Vr[i];if(!s){if((s=new Hr(i,e)).errors)return console.log(s.errors.join("\n")),null;Vr[i]=s,se.memory.programs++}return s._useCount++,s},Hr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Vr[this._hash],se.memory.programs--)},Hr.prototype.webglContextRestored=function(){this._program=null},Hr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){var n=s.backfaces;e.backfaces!==n&&(n?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=n);var o=s.frontface;e.frontface!==o&&(o?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=o),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){var a=t.vertexBufs;a.id!==this._lastVertexBufsId&&(a.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=a.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Hr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Ft(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(var r=0,n=t._sectionPlanesState.sectionPlanes.length;r0)for(var r,n,o,a=0,l=this._uSectionPlanes.length;a1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r)).originalSystemId=r.originalSystemId||s.id,s.renderFlags=new jr,s._state=new Jt({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==r.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!r.stationary,background:!!r.background,billboard:s._checkBillboard(r.billboard),layer:null,colorize:null,pickID:s.scene._renderer.getPickID(b(s)),drawHash:"",pickHash:"",offset:$.vec3(),origin:null,originHash:null}),s._drawRenderer=null,s._shadowRenderer=null,s._emphasisFillRenderer=null,s._emphasisEdgesRenderer=null,s._pickMeshRenderer=null,s._pickTriangleRenderer=null,s._occlusionRenderer=null,s._geometry=r.geometry?s._checkComponent2(["ReadableGeometry","VBOGeometry"],r.geometry):s.scene.geometry,s._material=r.material?s._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],r.material):s.scene.material,s._xrayMaterial=r.xrayMaterial?s._checkComponent("EmphasisMaterial",r.xrayMaterial):s.scene.xrayMaterial,s._highlightMaterial=r.highlightMaterial?s._checkComponent("EmphasisMaterial",r.highlightMaterial):s.scene.highlightMaterial,s._selectedMaterial=r.selectedMaterial?s._checkComponent("EmphasisMaterial",r.selectedMaterial):s.scene.selectedMaterial,s._edgeMaterial=r.edgeMaterial?s._checkComponent("EdgeMaterial",r.edgeMaterial):s.scene.edgeMaterial,s._parentNode=null,s._aabb=null,s._aabbDirty=!0,s._numTriangles=s._geometry?s._geometry.numTriangles:0,s.scene._aabbDirty=!0,s._scale=$.vec3(),s._quaternion=$.identityQuaternion(),s._rotation=$.vec3(),s._position=$.vec3(),s._worldMatrix=$.identityMat4(),s._worldNormalMatrix=$.identityMat4(),s._localMatrixDirty=!0,s._worldMatrixDirty=!0,s._worldNormalMatrixDirty=!0;var n=r.origin||r.rtcCenter;if(n&&(s._state.origin=$.vec3(n),s._state.originHash=n.join()),r.matrix?s.matrix=r.matrix:(s.scale=r.scale,s.position=r.position,r.quaternion||(s.rotation=r.rotation)),s._isObject=r.isObject,s._isObject&&s.scene._registerObject(b(s)),s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.layer=r.layer,s.colorize=r.colorize,s.opacity=r.opacity,s.offset=r.offset,r.parentId){var o=s.scene.components[r.parentId];o?o.isNode?o.addChild(b(s)):s.error("Parent is not a Node: '"+r.parentId+"'"):s.error("Parent not found: '"+r.parentId+"'"),s._parentNode=o}else r.parent&&(r.parent.isNode||s.error("Parent is not a Node"),r.parent.addChild(b(s)),s._parentNode=r.parent);return s.compile(),s}return C(i,[{key:"type",get:function(){return"Mesh"}},{key:"isMesh",get:function(){return!0}},{key:"parent",get:function(){return this._parentNode}},{key:"geometry",get:function(){return this._geometry}},{key:"material",get:function(){return this._material}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=$.identityMat4()),$.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix},set:function(e){this.__localMatrix||(this.__localMatrix=$.identityMat4()),this.__localMatrix.set(e||$r),$.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._aabbDirty&&this._updateAABB(),this._aabb}},{key:"origin",get:function(){return this._state.origin},set:function(e){e?(this._state.origin||(this._state.origin=$.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"rtcCenter",get:function(){return this.origin},set:function(e){this.origin=e}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._state.visible},set:function(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}},{key:"xrayed",get:function(){return this._state.xrayed},set:function(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}},{key:"highlighted",get:function(){return this._state.highlighted},set:function(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}},{key:"selected",get:function(){return this._state.selected},set:function(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}},{key:"culled",get:function(){return this._state.culled},set:function(e){this._state.culled=!!e,this.glRedraw()}},{key:"clippable",get:function(){return this._state.clippable},set:function(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}},{key:"collidable",get:function(){return this._state.collidable},set:function(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"pickable",get:function(){return this._state.pickable},set:function(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._state.receivesShadow},set:function(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}},{key:"saoEnabled",get:function(){return!1}},{key:"colorize",get:function(){return this._state.colorize},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);var i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}},{key:"opacity",get:function(){return this._state.colorize[3]},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1);var i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}},{key:"transparent",get:function(){return 2===this._material.alphaMode||this._state.colorize[3]<1}},{key:"layer",get:function(){return this._state.layer},set:function(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}},{key:"stationary",get:function(){return this._state.stationary}},{key:"billboard",get:function(){return this._state.billboard}},{key:"offset",get:function(){return this._state.offset},set:function(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!0}},{key:"xrayMaterial",get:function(){return this._xrayMaterial}},{key:"highlightMaterial",get:function(){return this._highlightMaterial}},{key:"selectedMaterial",get:function(){return this._selectedMaterial}},{key:"edgeMaterial",get:function(){return this._edgeMaterial}},{key:"_checkBillboard",value:function(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}},{key:"compile",value:function(){var e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=vr.get(this),this._emphasisFillRenderer=br.get(this),this._emphasisEdgesRenderer=Cr.get(this));var t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=kr.get(this)),this._state.occluder){var i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=Or.get(this))}}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}},{key:"_setWorldMatrixDirty",value:function(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentNode)$.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t0)for(var i=0;i-1){var R=k.geometry._state,L=k.scene,U=L.camera,O=L.canvas;if("triangles"===R.primitiveName){S.primitive="triangle";var N,Q,H,V=T,j=R.indices,G=R.positions;if(j){var z=j[V+0],K=j[V+1],W=j[V+2];n[0]=z,n[1]=K,n[2]=W,S.indices=n,N=3*z,Q=3*K,H=3*W}else H=(Q=(N=3*V)+3)+3;if(i[0]=G[N+0],i[1]=G[N+1],i[2]=G[N+2],s[0]=G[Q+0],s[1]=G[Q+1],s[2]=G[Q+2],r[0]=G[H+0],r[1]=G[H+1],r[2]=G[H+2],R.compressGeometry){var X=R.positionsDecodeMatrix;X&&(Fi.decompressPosition(i,X,i),Fi.decompressPosition(s,X,s),Fi.decompressPosition(r,X,r))}S.canvasPos?$.canvasPosToLocalRay(O.canvas,k.origin?Te(I,k.origin):I,D,k.worldMatrix,S.canvasPos,e,t):S.origin&&S.direction&&$.worldRayToLocalRay(k.worldMatrix,S.origin,S.direction,e,t),$.normalizeVec3(t),$.rayPlaneIntersect(e,t,i,s,r,o),S.localPos=o,S.position=o,v[0]=o[0],v[1]=o[1],v[2]=o[2],v[3]=1,$.transformVec4(k.worldMatrix,v,g),a[0]=g[0],a[1]=g[1],a[2]=g[2],S.canvasPos&&k.origin&&(a[0]+=k.origin[0],a[1]+=k.origin[1],a[2]+=k.origin[2]),S.worldPos=a,$.transformVec4(U.matrix,g,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],S.viewPos=l,$.cartesianToBarycentric(o,i,s,r,u),S.bary=u;var J=R.normals;if(J){if(R.compressGeometry){var Y=3*z,Z=3*K,q=3*W;Fi.decompressNormal(J.subarray(Y,Y+2),A),Fi.decompressNormal(J.subarray(Z,Z+2),c),Fi.decompressNormal(J.subarray(q,q+2),h)}else A[0]=J[N],A[1]=J[N+1],A[2]=J[N+2],c[0]=J[Q],c[1]=J[Q+1],c[2]=J[Q+2],h[0]=J[H],h[1]=J[H+1],h[2]=J[H+2];var ee=$.addVec3($.addVec3($.mulVec3Scalar(A,u[0],_),$.mulVec3Scalar(c,u[1],y),b),$.mulVec3Scalar(h,u[2],B),x);S.worldNormal=$.normalizeVec3($.transformVec3(k.worldNormalMatrix,ee,w))}var te=R.uv;if(te){if(d[0]=te[2*z],d[1]=te[2*z+1],p[0]=te[2*K],p[1]=te[2*K+1],f[0]=te[2*W],f[1]=te[2*W+1],R.compressGeometry){var ie=R.uvDecodeMatrix;ie&&(Fi.decompressUV(d,ie,d),Fi.decompressUV(p,ie,p),Fi.decompressUV(f,ie,f))}S.uv=$.addVec3($.addVec3($.mulVec2Scalar(d,u[0],P),$.mulVec2Scalar(p,u[1],C),M),$.mulVec2Scalar(f,u[2],F),E)}}}}}();function sn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);var i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);var s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);var r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);var n=e.heightSegments||1;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n<1&&(n=1);var o,a,l,u,A,c,h,d,p,f,v,g=!!e.openEnded,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,B=s/2,x=s/n,w=2*Math.PI/r,P=1/r,C=(t-i)/n,M=[],F=[],E=[],k=[],I=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(o=0;o<=n;o++)for(A=t-o*C,c=B-o*x,a=0;a<=r;a++)l=Math.sin(a*w),u=Math.cos(a*w),F.push(A*l),F.push(I),F.push(A*u),E.push(a*P),E.push(1*o/n),M.push(A*l+_),M.push(c+y),M.push(A*u+b);for(o=0;o0){for(p=M.length/3,F.push(0),F.push(1),F.push(0),E.push(.5),E.push(.5),M.push(0+_),M.push(B+y),M.push(0+b),a=0;a<=r;a++)l=Math.sin(a*w),u=Math.cos(a*w),f=.5*Math.sin(a*w)+.5,v=.5*Math.cos(a*w)+.5,F.push(t*l),F.push(1),F.push(t*u),E.push(f),E.push(v),M.push(t*l+_),M.push(B+y),M.push(t*u+b);for(a=0;a0){for(p=M.length/3,F.push(0),F.push(-1),F.push(0),E.push(.5),E.push(.5),M.push(0+_),M.push(0-B+y),M.push(0+b),a=0;a<=r;a++)l=Math.sin(a*w),u=Math.cos(a*w),f=.5*Math.sin(a*w)+.5,v=.5*Math.cos(a*w)+.5,F.push(i*l),F.push(-1),F.push(i*u),E.push(f),E.push(v),M.push(i*l+_),M.push(0-B+y),M.push(i*u+b);for(a=0;a0&&void 0!==arguments[0]?arguments[0]:{},t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0,n=e.radius||1;n<0&&(console.error("negative radius not allowed - will invert"),n*=-1);var o=e.heightSegments||18;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),(o=Math.floor(t*o))<18&&(o=18);var a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);var l,u,A,c,h,d,p,f,v,g,m,_,y,b,B=[],x=[],w=[],P=[];for(l=0;l<=o;l++)for(A=l*Math.PI/o,c=Math.sin(A),h=Math.cos(A),u=0;u<=a;u++)d=2*u*Math.PI/a,p=Math.sin(d),f=Math.cos(d)*c,v=h,g=p*c,m=1-u/a,_=l/o,x.push(f),x.push(v),x.push(g),w.push(m),w.push(_),B.push(i+n*f),B.push(s+n*v),B.push(r+n*g);for(l=0;l":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function on(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],n=e.size||1,o=[],a=[],l=e.text;le.isNumeric(l)&&(l=""+l);for(var u,A,c,h,d,p,f,v,g,m=(l||"").split("\n"),_=0,y=0,b=.04,B=0;B1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({active:!0,pos:$.vec3(),dir:$.vec3(),dist:0}),s.active=r.active,s.pos=r.pos,s.dir=r.dir,s.scene._sectionPlaneCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"SectionPlane"}},{key:"active",get:function(){return this._state.active},set:function(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dist",get:function(){return this._state.dist}},{key:"flipDir",value:function(){var e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}},{key:"destroy",value:function(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),un=$.vec4(4),An=$.vec4(),cn=$.vec4(),hn=$.vec3([1,0,0]),dn=$.vec3([0,1,0]),pn=$.vec3([0,0,1]),fn=$.vec3(3),vn=$.vec3(3),gn=$.identityMat4(),mn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e,r))._parentNode=null,s._children=[],s._aabb=null,s._aabbDirty=!0,s.scene._aabbDirty=!0,s._numTriangles=0,s._scale=$.vec3(),s._quaternion=$.identityQuaternion(),s._rotation=$.vec3(),s._position=$.vec3(),s._offset=$.vec3(),s._localMatrix=$.identityMat4(),s._worldMatrix=$.identityMat4(),s._localMatrixDirty=!0,s._worldMatrixDirty=!0,r.matrix?s.matrix=r.matrix:(s.scale=r.scale,s.position=r.position,r.quaternion||(s.rotation=r.rotation)),s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s._isObject=r.isObject,s._isObject&&s.scene._registerObject(b(s)),s.origin=r.origin,s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.colorize=r.colorize,s.opacity=r.opacity,s.offset=r.offset,r.children)for(var n=r.children,o=0,a=n.length;o1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"LambertMaterial",ambient:$.vec3([1,1,1]),color:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),s.ambient=r.ambient,s.color=r.color,s.emissive=r.emissive,s.alpha=r.alpha,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s.backfaces=r.backfaces,s.frontface=r.frontface,s}return C(i,[{key:"type",get:function(){return"LambertMaterial"}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){var t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),yn={opaque:0,mask:1,blend:2},bn=["opaque","mask","blend"],Bn=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"MetallicMaterial",baseColor:$.vec4([1,1,1]),emissive:$.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.baseColor=r.baseColor,s.metallic=r.metallic,s.roughness=r.roughness,s.specularF0=r.specularF0,s.emissive=r.emissive,s.alpha=r.alpha,r.baseColorMap&&(s._baseColorMap=s._checkComponent("Texture",r.baseColorMap)),r.metallicMap&&(s._metallicMap=s._checkComponent("Texture",r.metallicMap)),r.roughnessMap&&(s._roughnessMap=s._checkComponent("Texture",r.roughnessMap)),r.metallicRoughnessMap&&(s._metallicRoughnessMap=s._checkComponent("Texture",r.metallicRoughnessMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"MetallicMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"baseColor",get:function(){return this._state.baseColor},set:function(e){var t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"baseColorMap",get:function(){return this._baseColorMap}},{key:"metallic",get:function(){return this._state.metallic},set:function(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}},{key:"metallicMap",get:function(){return this._attached.metallicMap}},{key:"roughness",get:function(){return this._state.roughness},set:function(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}},{key:"roughnessMap",get:function(){return this._attached.roughnessMap}},{key:"metallicRoughnessMap",get:function(){return this._attached.metallicRoughnessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._attached.emissiveMap}},{key:"occlusionMap",get:function(){return this._attached.occlusionMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._attached.alphaMap}},{key:"normalMap",get:function(){return this._attached.normalMap}},{key:"alphaMode",get:function(){return bn[this._state.alphaMode]},set:function(e){var t=yn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),xn={opaque:0,mask:1,blend:2},wn=["opaque","mask","blend"],Pn=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"SpecularMaterial",diffuse:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),specular:$.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.diffuse=r.diffuse,s.specular=r.specular,s.glossiness=r.glossiness,s.specularF0=r.specularF0,s.emissive=r.emissive,s.alpha=r.alpha,r.diffuseMap&&(s._diffuseMap=s._checkComponent("Texture",r.diffuseMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.specularMap&&(s._specularMap=s._checkComponent("Texture",r.specularMap)),r.glossinessMap&&(s._glossinessMap=s._checkComponent("Texture",r.glossinessMap)),r.specularGlossinessMap&&(s._specularGlossinessMap=s._checkComponent("Texture",r.specularGlossinessMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"SpecularMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specularMap",get:function(){return this._specularMap}},{key:"specularGlossinessMap",get:function(){return this._specularGlossinessMap}},{key:"glossiness",get:function(){return this._state.glossiness},set:function(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}},{key:"glossinessMap",get:function(){return this._glossinessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"normalMap",get:function(){return this._normalMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"alphaMode",get:function(){return wn[this._state.alphaMode]},set:function(e){var t=xn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function Cn(e,t){var i,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===s){var n=zt(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===n)return null;if(33776===r)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(null===(i=zt(e,"WEBGL_compressed_texture_s3tc")))return null;if(33776===r)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){var o=zt(e,"WEBGL_compressed_texture_pvrtc");if(null===o)return null;if(35840===r)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){var a=zt(e,"WEBGL_compressed_texture_etc1");return null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){var l=zt(e,"WEBGL_compressed_texture_etc");if(null===l)return null;if(37492===r)return 3001===s?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===s?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){var u=zt(e,"WEBGL_compressed_texture_astc");if(null===u)return null;if(37808===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:u.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:u.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:u.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:u.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:u.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:u.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:u.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:u.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:u.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:u.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:u.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:u.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:u.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:u.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){var A=zt(e,"EXT_texture_compression_bptc");if(null===A)return null;if(36492===r)return 3001===s?A.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:A.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}var Mn=new Uint8Array([0,0,0,1]),Fn=function(){function e(t){var i=t.gl,s=t.target,r=t.format,n=t.type,o=t.wrapS,a=t.wrapT,l=t.wrapR,u=t.encoding,A=t.preloadColor,c=t.premultiplyAlpha,h=t.flipY;w(this,e),this.gl=i,this.target=s||i.TEXTURE_2D,this.format=r||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!h,this.unpackAlignment=4,this.wrapS=o||1e3,this.wrapT=a||1e3,this.wrapR=l||1e3,this.encoding=u||3001,this.texture=i.createTexture(),A&&this.setPreloadColor(A),this.allocated=!0}return C(e,[{key:"setPreloadColor",value:function(e){e?(Mn[0]=Math.floor(255*e[0]),Mn[1]=Math.floor(255*e[1]),Mn[2]=Math.floor(255*e[2]),Mn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Mn[0]=0,Mn[1]=0,Mn[2]=0,Mn[3]=255);var t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP)for(var i=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z],s=0,r=i.length;s1&&void 0!==arguments[1]?arguments[1]:{},i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);var s=!1;i.bindTexture(this.target,this.texture);var r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);var n=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var o=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);var a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);var l=Cn(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(s=!0);var u=Cn(i,this.magFilter);u&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,u);var A=Cn(i,this.wrapS);A&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,A);var c=Cn(i,this.wrapT);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,c);var h=Cn(i,this.format,this.encoding),d=Cn(i,this.type),p=En(i,this.internalFormat,h,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(le.isArray(e))for(var f=e,v=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z],g=0,m=v.length;g1;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,this.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,this.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,r.NONE);var a=Cn(r,this.wrapS);a&&r.texParameteri(this.target,r.TEXTURE_WRAP_S,a);var l=Cn(r,this.wrapT);if(l&&r.texParameteri(this.target,r.TEXTURE_WRAP_T,l),this.type===r.TEXTURE_3D||this.type===r.TEXTURE_2D_ARRAY){var u=Cn(r,this.wrapR);u&&r.texParameteri(this.target,r.TEXTURE_WRAP_R,u),r.texParameteri(this.type,r.TEXTURE_WRAP_R,u)}o?(r.texParameteri(this.target,r.TEXTURE_MIN_FILTER,kn(r,this.minFilter)),r.texParameteri(this.target,r.TEXTURE_MAG_FILTER,kn(r,this.magFilter))):(r.texParameteri(this.target,r.TEXTURE_MIN_FILTER,Cn(r,this.minFilter)),r.texParameteri(this.target,r.TEXTURE_MAG_FILTER,Cn(r,this.magFilter)));var A=Cn(r,this.format,this.encoding),c=Cn(r,this.type),h=En(r,this.internalFormat,A,c,this.encoding,!1);r.texStorage2D(r.TEXTURE_2D,n,h,t[0].width,t[0].height);for(var d=0,p=t.length;d5&&void 0!==arguments[5]&&arguments[5];if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}var o=i;return i===e.RED&&(s===e.FLOAT&&(o=e.R32F),s===e.HALF_FLOAT&&(o=e.R16F),s===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RG&&(s===e.FLOAT&&(o=e.RG32F),s===e.HALF_FLOAT&&(o=e.RG16F),s===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(o=e.RGBA32F),s===e.HALF_FLOAT&&(o=e.RGBA16F),s===e.UNSIGNED_BYTE&&(o=3001===r&&!1===n?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)),o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||zt(e,"EXT_color_buffer_float"),o}function kn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function In(e){if(!Dn(e.width)||!Dn(e.height)){var t=document.createElement("canvas");t.width=Sn(e.width),t.height=Sn(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Dn(e){return 0==(e&e-1)}function Sn(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var Tn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({texture:new Fn({gl:s.scene.canvas.gl}),matrix:$.identityMat4(),hasMatrix:r.translate&&(0!==r.translate[0]||0!==r.translate[1])||!!r.rotate||r.scale&&(0!==r.scale[0]||0!==r.scale[1]),minFilter:s._checkMinFilter(r.minFilter),magFilter:s._checkMagFilter(r.magFilter),wrapS:s._checkWrapS(r.wrapS),wrapT:s._checkWrapT(r.wrapT),flipY:s._checkFlipY(r.flipY),encoding:s._checkEncoding(r.encoding)}),s._src=null,s._image=null,s._translate=$.vec2([0,0]),s._scale=$.vec2([1,1]),s._rotate=$.vec2([0,0]),s._matrixDirty=!1,s.translate=r.translate,s.scale=r.scale,s.rotate=r.rotate,r.src?s.src=r.src:r.image&&(s.image=r.image),se.memory.textures++,s}return C(i,[{key:"type",get:function(){return"Texture"}},{key:"_checkMinFilter",value:function(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}},{key:"_checkMagFilter",value:function(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}},{key:"_checkWrapS",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkWrapT",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this._state.texture=new Fn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}},{key:"_update",value:function(){var e,t,i=this._state;this._matrixDirty&&(0===this._translate[0]&&0===this._translate[1]||(e=$.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(t=$.scalingMat4v([this._scale[0],this._scale[1],1]),e=e?$.mulMat4(e,t):t),0!==this._rotate&&(t=$.rotationMat4v(.0174532925*this._rotate,[0,0,1]),e=e?$.mulMat4(e,t):t),e&&(i.matrix=e),this._matrixDirty=!1);this.glRedraw()}},{key:"image",get:function(){return this._image},set:function(e){this._image=In(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}},{key:"src",get:function(){return this._src},set:function(e){this.scene.loading++,this.scene.canvas.spinner.processes++;var t=this,i=new Image;i.onload=function(){i=In(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}},{key:"translate",get:function(){return this._translate},set:function(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}},{key:"rotate",get:function(){return this._rotate},set:function(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}},{key:"minFilter",get:function(){return this._state.minFilter}},{key:"magFilter",get:function(){return this._state.magFilter}},{key:"wrapS",get:function(){return this._state.wrapS}},{key:"wrapT",get:function(){return this._state.wrapT}},{key:"flipY",get:function(){return this._state.flipY}},{key:"encoding",get:function(){return this._state.encoding}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),se.memory.textures--}}]),i}(),Rn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({edgeColor:$.vec3([0,0,0]),centerColor:$.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),s.edgeColor=r.edgeColor,s.centerColor=r.centerColor,s.edgeBias=r.edgeBias,s.centerBias=r.centerBias,s.power=r.power,s}return C(i,[{key:"type",get:function(){return"Fresnel"}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}},{key:"centerColor",get:function(){return this._state.centerColor},set:function(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}},{key:"edgeBias",get:function(){return this._state.edgeBias},set:function(e){this._state.edgeBias=e||0,this.glRedraw()}},{key:"centerBias",get:function(){return this._state.centerBias},set:function(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}},{key:"power",get:function(){return this._state.power},set:function(e){this._state.power=null!=e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ln=se.memory,Un=$.AABB3(),On=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._state=new Jt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),s._numTriangles=0,s._edgeThreshold=r.edgeThreshold||10,s._aabb=null,s._obb=$.OBB3();var n,o=s._state,a=s.scene.canvas.gl;switch(r.primitive=r.primitive||"triangles",r.primitive){case"points":o.primitive=a.POINTS,o.primitiveName=r.primitive;break;case"lines":o.primitive=a.LINES,o.primitiveName=r.primitive;break;case"line-loop":o.primitive=a.LINE_LOOP,o.primitiveName=r.primitive;break;case"line-strip":o.primitive=a.LINE_STRIP,o.primitiveName=r.primitive;break;case"triangles":o.primitive=a.TRIANGLES,o.primitiveName=r.primitive;break;case"triangle-strip":o.primitive=a.TRIANGLE_STRIP,o.primitiveName=r.primitive;break;case"triangle-fan":o.primitive=a.TRIANGLE_FAN,o.primitiveName=r.primitive;break;default:s.error("Unsupported value for 'primitive': '"+r.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),o.primitive=a.TRIANGLES,o.primitiveName=r.primitive}if(!r.positions)return s.error("Config expected: positions"),y(s);if(!r.indices)return s.error("Config expected: indices"),y(s);var l=r.positionsDecodeMatrix;if(l);else{var u=Fi.getPositionsBounds(r.positions),A=Fi.compressPositions(r.positions,u.min,u.max);n=A.quantized,o.positionsDecodeMatrix=A.decodeMatrix,o.positionsBuf=new Et(a,a.ARRAY_BUFFER,n,n.length,3,a.STATIC_DRAW),Ln.positions+=o.positionsBuf.numItems,$.positions3ToAABB3(r.positions,s._aabb),$.positions3ToAABB3(n,Un,o.positionsDecodeMatrix),$.AABB3ToOBB3(Un,s._obb)}if(r.colors){var c=r.colors.constructor===Float32Array?r.colors:new Float32Array(r.colors);o.colorsBuf=new Et(a,a.ARRAY_BUFFER,c,c.length,4,a.STATIC_DRAW),Ln.colors+=o.colorsBuf.numItems}if(r.uv){var h=Fi.getUVBounds(r.uv),d=Fi.compressUVs(r.uv,h.min,h.max),p=d.quantized;o.uvDecodeMatrix=d.decodeMatrix,o.uvBuf=new Et(a,a.ARRAY_BUFFER,p,p.length,2,a.STATIC_DRAW),Ln.uvs+=o.uvBuf.numItems}if(r.normals){var f=Fi.compressNormals(r.normals),v=o.compressGeometry;o.normalsBuf=new Et(a,a.ARRAY_BUFFER,f,f.length,3,a.STATIC_DRAW,v),Ln.normals+=o.normalsBuf.numItems}var g=r.indices.constructor===Uint32Array||r.indices.constructor===Uint16Array?r.indices:new Uint32Array(r.indices);o.indicesBuf=new Et(a,a.ELEMENT_ARRAY_BUFFER,g,g.length,1,a.STATIC_DRAW),Ln.indices+=o.indicesBuf.numItems;var m=bi(n,g,o.positionsDecodeMatrix,s._edgeThreshold);return s._edgeIndicesBuf=new Et(a,a.ELEMENT_ARRAY_BUFFER,m,m.length,1,a.STATIC_DRAW),"triangles"===s._state.primitiveName&&(s._numTriangles=r.indices.length/3),s._buildHash(),Ln.meshes++,s}return C(i,[{key:"type",get:function(){return"VBOGeometry"}},{key:"isVBOGeometry",get:function(){return!0}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"aabb",get:function(){return this._aabb}},{key:"obb",get:function(){return this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Ln.meshes--}}]),i}(),Nn={};function Qn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var n=Nn.parse.from3DS(e).edit.objects[0].mesh,o=n.vertices,a=n.uvt,l=n.indices;r.processes--,i(le.apply(t,{primitive:"triangles",positions:o,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function Hn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var n=Nn.parse.fromOBJ(e),o=Nn.edit.unwrap(n.i_verts,n.c_verts,3),a=Nn.edit.unwrap(n.i_norms,n.c_norms,3),l=Nn.edit.unwrap(n.i_uvt,n.c_uvt,2),u=new Int32Array(n.i_verts.length),A=0;A0?a:null,autoNormals:0===a.length,uv:l,indices:u}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function Vn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);var r=e.center,n=r?r[0]:0,o=r?r[1]:0,a=r?r[2]:0,l=-t+n,u=-i+o,A=-s+a,c=t+n,h=i+o,d=s+a;return le.apply(e,{primitive:"lines",positions:[l,u,A,l,u,d,l,h,A,l,h,d,c,u,A,c,u,d,c,h,A,c,h,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function jn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Vn({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function Gn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);var i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1);for(var s=(t=t||10)/(i=i||10),r=t/2,n=[],o=[],a=0,l=0,u=-r;l<=i;l++,u+=s)n.push(-r),n.push(0),n.push(u),n.push(r),n.push(0),n.push(u),n.push(u),n.push(0),n.push(-r),n.push(u),n.push(0),n.push(r),o.push(a++),o.push(a++),o.push(a++),o.push(a++);return le.apply(e,{primitive:"lines",positions:n,indices:o})}function zn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);var s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);var r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);var n,o,a,l,u,A,c,h=e.center,d=h?h[0]:0,p=h?h[1]:0,f=h?h[2]:0,v=t/2,g=i/2,m=Math.floor(s)||1,_=Math.floor(r)||1,y=m+1,b=_+1,B=t/m,x=i/_,w=new Float32Array(y*b*3),P=new Float32Array(y*b*3),C=new Float32Array(y*b*2),M=0,F=0;for(n=0;n65535?Uint32Array:Uint16Array)(m*_*6);for(n=0;n<_;n++)for(o=0;o0&&void 0!==arguments[0]?arguments[0]:{},t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;var i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);var s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);var r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);var n=e.arc||2*Math.PI;n<0&&(console.warn("negative arc not allowed - will invert"),n*=-1),n>360&&(n=360);var o,a,l,u,A,c,h,d,p,f,v,g,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,B=[],x=[],w=[],P=[];for(d=0;d<=r;d++)for(h=0;h<=s;h++)o=h/s*n,a=.785398+d/r*Math.PI*2,_=t*Math.cos(o),y=t*Math.sin(o),l=(t+i*Math.cos(a))*Math.cos(o),u=(t+i*Math.cos(a))*Math.sin(o),A=i*Math.sin(a),B.push(l+_),B.push(u+y),B.push(A+b),w.push(1-h/s),w.push(d/r),c=$.normalizeVec3($.subVec3([l,u,A],[_,y,b],[]),[]),x.push(c[0]),x.push(c[1]),x.push(c[2]);for(d=1;d<=r;d++)for(h=1;h<=s;h++)p=(s+1)*d+h-1,f=(s+1)*(d-1)+h-1,v=(s+1)*(d-1)+h,g=(s+1)*d+h,P.push(p),P.push(f),P.push(v),P.push(v),P.push(g),P.push(p);return le.apply(e,{positions:B,normals:x,uv:w,indices:P})}function Wn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";var t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";for(var i=[],s=0;s0&&void 0!==arguments[0]?arguments[0]:{},t=e.curve.getPoints(e.divisions).map((function(e){return A(e)})).flat();return Wn({id:e.id,points:t})}Nn.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},Nn.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(Nn.parse._buffToStr(e));window.location.href=i},Nn.clone=function(e){return JSON.parse(JSON.stringify(e))},Nn.bin={},Nn.bin.f=new Float32Array(1),Nn.bin.fb=new Uint8Array(Nn.bin.f.buffer),Nn.bin.rf=function(e,t){for(var i=Nn.bin.f,s=Nn.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Nn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Nn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Nn.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Nn.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Nn.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Nn.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Nn.parse={},Nn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),un&&(n=u),Ao&&(o=A)}return{min:{x:t,y:i,z:s},max:{x:r,y:n,z:o}}};var Jn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._type=r.type||(r.src?r.src.split(".").pop():null)||"jpg",s._pos=$.vec3(r.pos||[0,0,0]),s._up=$.vec3(r.up||[0,1,0]),s._normal=$.vec3(r.normal||[0,0,1]),s._height=r.height||1,s._origin=$.vec3(),s._rtcPos=$.vec3(),s._imageSize=$.vec2(),s._texture=new Tn(b(s),{flipY:!0}),s._image=new Image,"jpg"!==s._type&&"png"!==s._type&&(s.error('Unsupported type - defaulting to "jpg"'),s._type="jpg"),s._node=new mn(b(s),{matrix:$.inverseMat4($.lookAtMat4v(s._pos,$.subVec3(s._pos,s._normal,$.mat4()),s._up,$.mat4())),children:[s._bitmapMesh=new en(b(s),{scale:[1,1,1],rotation:[-90,0,0],collidable:r.collidable,pickable:r.pickable,opacity:r.opacity,clippable:r.clippable,geometry:new Ii(b(s),zn({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Li(b(s),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:s._texture,emissiveMap:s._texture,backfaces:!0})})]}),r.image?s.image=r.image:r.src?s.src=r.src:r.imageData&&(s.imageData=r.imageData),s.scene._bitmapCreated(b(s)),s}return C(i,[{key:"visible",get:function(){return this._bitmapMesh.visible},set:function(e){this._bitmapMesh.visible=e}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}},{key:"src",get:function(){return this._image.src},set:function(e){var t=this;if(e)switch(this._image.onload=function(){t._texture.image=t._image,t._imageSize[0]=t._image.width,t._imageSize[1]=t._image.height,t._updateBitmapMeshScale()},this._image.src=e,e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}},{key:"imageData",get:function(){var e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")},set:function(e){var t=this;this._image.onload=function(){t._texture.image=image,t._imageSize[0]=image.width,t._imageSize[1]=image.height,t._updateBitmapMeshScale()},this._image.src=e}},{key:"type",get:function(){return this._type},set:function(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}},{key:"pos",get:function(){return this._pos}},{key:"normal",get:function(){return this._normal}},{key:"up",get:function(){return this._up}},{key:"height",get:function(){return this._height},set:function(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}},{key:"collidable",get:function(){return this._bitmapMesh.collidable},set:function(e){this._bitmapMesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._bitmapMesh.clippable},set:function(e){this._bitmapMesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._bitmapMesh.pickable},set:function(e){this._bitmapMesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._bitmapMesh.opacity},set:function(e){this._bitmapMesh.opacity=e}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._bitmapDestroyed(this)}},{key:"_updateBitmapMeshScale",value:function(){var e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}]),i}(),Yn=$.OBB3(),Zn=$.OBB3(),qn=$.OBB3(),$n=function(){function e(t,i,s,r,n,o){var a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0;w(this,e),this.model=t,this.object=null,this.parent=null,this.transform=n,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=i,this.obb=null,this._aabbLocal=null,this._aabbWorld=$.AABB3(),this._aabbWorldDirty=!1,this.layer=a,this.portionId=l,this._color=new Uint8Array([s[0],s[1],s[2],r]),this._colorize=new Uint8Array([s[0],s[1],s[2],r]),this._colorizing=!1,this._transparent=r<255,this.numTriangles=0,this.origin=null,this.entity=null,n&&n._addMesh(this)}return C(e,[{key:"_sceneModelDirty",value:function(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}},{key:"_updateMatrix",value:function(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}},{key:"_finalize",value:function(e){this.layer.initFlags(this.portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this.layer.setVisible(this.portionId,e,this._transparent)}},{key:"_setColor",value:function(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)}},{key:"_setColorize",value:function(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)}},{key:"_setOpacity",value:function(e,t){var i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}},{key:"_setOffset",value:function(e){this.layer.setOffset(this.portionId,e)}},{key:"_setHighlighted",value:function(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this.layer.setXRayed(this.portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this.layer.setSelected(this.portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this.layer.setEdges(this.portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this.layer.setClippable(this.portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this.layer.setCollidable(this.portionId,e)}},{key:"_setPickable",value:function(e){this.layer.setPickable(this.portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this.layer.setCulled(this.portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"getEachVertex",value:function(e){this.layer.getEachVertex(this.portionId,e)}},{key:"aabb",get:function(){if(this._aabbWorldDirty){if($.AABB3ToOBB3(this._aabbLocal,Yn),this.transform?($.transformOBB3(this.transform.worldMatrix,Yn,Zn),$.transformOBB3(this.model.worldMatrix,Zn,qn),$.OBB3ToAABB3(qn,this._aabbWorld)):($.transformOBB3(this.model.worldMatrix,Yn,Zn),$.OBB3ToAABB3(Zn,this._aabbWorld)),this.origin){var e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld},set:function(e){this._aabbLocal=e}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),eo=new(function(){function e(){w(this,e),this._uint8Arrays={},this._float32Arrays={}}return C(e,[{key:"_clear",value:function(){this._uint8Arrays={},this._float32Arrays={}}},{key:"getUInt8Array",value:function(e){var t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}},{key:"getFloat32Array",value:function(e){var t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}}]),e}()),to=0;function io(){return to++,eo}var so={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},ro=new Float32Array([1,1,1,1]),no=new Float32Array([0,0,0,1]),oo=$.vec4(),ao=$.vec3(),lo=$.vec3(),uo=$.mat4(),Ao=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=s.instancing,n=void 0!==r&&r,o=s.edges,a=void 0!==o&&o;w(this,e),this._scene=t,this._withSAO=i,this._instancing=n,this._edges=a,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}return C(e,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){return[""]}},{key:"_buildFragmentShader",value:function(){return[""]}},{key:"_addMatricesUniformBlockLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}},{key:"_addRemapClipPosLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(".concat(t,"));")),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}},{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"setSectionPlanesStateUniforms",value:function(e){var t=this._scene,i=t.canvas.gl,s=e.model,r=e.layerIndex,n=t._sectionPlanesState.getNumAllocatedSectionPlanes(),o=t._sectionPlanesState.sectionPlanes.length;if(n>0)for(var a=t._sectionPlanesState.sectionPlanes,l=r*o,u=s.renderFlags,A=0;A0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,l=e._sectionPlanesState.getNumAllocatedSectionPlanes();a3&&void 0!==arguments[3]?arguments[3]:{},r=s.colorUniform,n=void 0!==r&&r,o=s.incrementDrawState,a=void 0!==o&&o,l=mt.MAX_TEXTURE_IMAGE_UNITS,u=this._scene,A=u.canvas.gl,c=t._state,h=t.model,d=c.textureSet,p=c.origin,f=c.positionsDecodeMatrix,v=u._lightsState,g=u.pointsMaterial,m=h.scene.camera,_=m.viewNormalMatrix,y=m.project,b=e.pickViewMatrix||m.viewMatrix,B=h.position,x=h.rotationMatrix,w=h.rotationMatrixConjugate,P=h.worldNormalMatrix;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?A.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(c));var C=0,M=16;this._matricesUniformBlockBufferData.set(w,0);var F=0!==p[0]||0!==p[1]||0!==p[2],E=0!==B[0]||0!==B[1]||0!==B[2];if(F||E){var k=ao;if(F){var I=$.transformPoint3(x,p,lo);k[0]=I[0],k[1]=I[1],k[2]=I[2]}else k[0]=0,k[1]=0,k[2]=0;k[0]+=B[0],k[1]+=B[1],k[2]+=B[2],this._matricesUniformBlockBufferData.set(Te(b,k,uo),C+=M)}else this._matricesUniformBlockBufferData.set(b,C+=M);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,C+=M),this._matricesUniformBlockBufferData.set(f,C+=M),this._matricesUniformBlockBufferData.set(P,C+=M),this._matricesUniformBlockBufferData.set(_,C+=M),A.bindBuffer(A.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),A.bufferData(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,A.DYNAMIC_DRAW),A.bindBufferBase(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),A.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),u.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var D=2/(Math.log(e.pickZFar+1)/Math.LN2);A.uniform1f(this._uLogDepthBufFC,D)}this._uZFar&&A.uniform1f(this._uZFar,u.camera.project.far)}if(this._uPickInvisible&&A.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&A.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&A.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&A.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&A.uniform2f(this._uDrawingBufferSize,A.drawingBufferWidth,A.drawingBufferHeight),this._uUVDecodeMatrix&&A.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._uIntensityRange&&g.filterIntensity&&A.uniform2f(this._uIntensityRange,g.minIntensity,g.maxIntensity),this._uPointSize&&A.uniform1f(this._uPointSize,g.pointSize),this._uNearPlaneHeight){var S="ortho"===u.camera.projection?1:A.drawingBufferHeight/(2*Math.tan(.5*u.camera.perspective.fov*Math.PI/180));A.uniform1f(this._uNearPlaneHeight,S)}if(d){var T=d.colorTexture,R=d.metallicRoughnessTexture,L=d.emissiveTexture,U=d.normalsTexture,O=d.occlusionTexture;this._uColorMap&&T&&(this._program.bindTexture(this._uColorMap,T.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uMetallicRoughMap&&R&&(this._program.bindTexture(this._uMetallicRoughMap,R.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uEmissiveMap&&L&&(this._program.bindTexture(this._uEmissiveMap,L.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uNormalMap&&U&&(this._program.bindTexture(this._uNormalMap,U.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uAOMap&&O&&(this._program.bindTexture(this._uAOMap,O.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l)}if(v.reflectionMaps.length>0&&v.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,v.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),v.lightMaps.length>0&&v.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,v.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),this._withSAO){var N=u.sao,Q=N.possible;if(Q){var H=A.drawingBufferWidth,V=A.drawingBufferHeight;oo[0]=H,oo[1]=V,oo[2]=N.blendCutoff,oo[3]=N.blendFactor,A.uniform4fv(this._uSAOParams,oo),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++}}if(n){var j=this._edges?"edgeColor":"fillColor",G=this._edges?"edgeAlpha":"fillAlpha";if(i===so["".concat(this._edges?"EDGES":"SILHOUETTE","_XRAYED")]){var z=u.xrayMaterial._state,K=z[j],W=z[G];A.uniform4f(this._uColor,K[0],K[1],K[2],W)}else if(i===so["".concat(this._edges?"EDGES":"SILHOUETTE","_HIGHLIGHTED")]){var X=u.highlightMaterial._state,J=X[j],Y=X[G];A.uniform4f(this._uColor,J[0],J[1],J[2],Y)}else if(i===so["".concat(this._edges?"EDGES":"SILHOUETTE","_SELECTED")]){var Z=u.selectedMaterial._state,q=Z[j],ee=Z[G];A.uniform4f(this._uColor,q[0],q[1],q[2],ee)}else A.uniform4fv(this._uColor,this._edges?no:ro)}this._draw({state:c,frameCtx:e,incrementDrawState:a}),A.bindVertexArray(null)}}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null,se.memory.programs--}}]),e}(),co=function(e){g(i,Ao);var t=_(i);function i(e,s){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.edges,o=void 0!==n&&n;return w(this,i),t.call(this,e,s,{instancing:!1,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{var n=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,n,i.indicesBuf.itemType,o),r&&s.drawElements++}}}]),i}(),ho=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,s=t._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Triangles batching draw vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in float flags;"),t.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),r&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),t.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=s.lights.length;l0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}]),i}(),po=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,o=i.getNumAllocatedSectionPlanes();n> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var A=0,c=i.getNumAllocatedSectionPlanes();A 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var h=0,d=t.lights.length;h0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}]),i}(),vo=function(e){g(i,co);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!1,edges:!0})}return C(i)}(),go=function(e){g(i,vo);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),mo=function(e){g(i,vo);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),_o=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}]),i}(),yo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),bo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Bo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),xo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}]),i}(),wo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Po=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}]),i}(),Co=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Triangles batching quality draw vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.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);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),r&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),n.push("vFragDepth = 1.0 + clipPos.w;")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Triangles batching quality draw fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),o.push("uniform sampler2D uAOMap;"),o.push("in vec4 vViewPosition;"),o.push("in vec3 vViewNormal;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=s.lights.length;a0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=s.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Fo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var o=0,a=s.getNumAllocatedSectionPlanes();o> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var c=0,h=s.getNumAllocatedSectionPlanes();c 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var d=0,p=i.lights.length;d0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ro=$.vec3(),Lo=$.vec3(),Uo=$.vec3(),Oo=$.vec3(),No=$.mat4(),Qo=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Ro;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Lo;if(l){var m=Uo;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,No),(f=Oo)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElements(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ho=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new fo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new _o(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new yo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new To(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Qo(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new ho(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new ho(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new po(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new po(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Fo(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Fo(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new Co(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Co(this._scene,!0)),this._pbrRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fo(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new xo(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new wo(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new go(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new mo(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new _o(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new bo(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Mo(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new yo(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Bo(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Po(this._scene)),this._shadowRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Qo(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new To(this._scene)),this._snapInitRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Vo={};var jo=65536,Go=5e6,zo=function(){function e(){w(this,e)}return C(e,[{key:"doublePrecisionEnabled",get:function(){return $.getDoublePrecisionEnabled()},set:function(e){$.setDoublePrecisionEnabled(e)}},{key:"maxDataTextureHeight",get:function(){return jo},set:function(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),jo=e}},{key:"maxGeometryBatchSize",get:function(){return Go},set:function(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Go=e}}]),e}(),Ko=new zo,Wo=C((function e(){w(this,e),this.maxVerts=Ko.maxGeometryBatchSize,this.maxIndices=3*Ko.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]})),Xo=$.mat4(),Jo=$.mat4();function Yo(e,t,i){for(var s=e.length,r=new Uint16Array(s),n=t[0],o=t[1],a=t[2],l=t[3]-n,u=t[4]-o,A=t[5]-a,c=65525,h=c/l,d=c/u,p=c/A,f=function(e){return e>=0?e:0},v=0;v=0?1:-1),o=(1-Math.abs(s))*(r>=0?1:-1),s=n,r=o}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function $o(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}var ea=$.mat4(),ta=$.mat4(),ia=$.vec4([0,0,0,1]),sa=$.vec3(),ra=$.vec3(),na=$.vec3(),oa=$.vec3(),aa=$.vec3(),la=$.vec3(),ua=$.vec3(),Aa=function(){function e(t){var i,s,r;w(this,e),console.info("Creating VBOBatchingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesBatchingLayer"+(t.solid?"-solid":"-surface")+(t.autoNormals?"-autonormals":"-normals")+(t.textureSet&&t.textureSet.colorTexture?"-colorTexture":"")+(t.textureSet&&t.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Vo[s])||(r=new Ho(i),Vo[s]=r,r._compile(),r.eagerCreateRenders(),i.on("compile",(function(){r._compile(),r.eagerCreateRenders()})),i.on("destroyed",(function(){delete Vo[s],r._destroy()}))),r),this._buffer=new Wo(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new Jt({origin:$.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:t.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)),t.uvDecodeMatrix?(this._state.uvDecodeMatrix=$.mat3(t.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,t.origin&&this._state.origin.set(t.origin),this.solid=!!t.solid}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)for(var C=0,M=o.length;C0){var F=ea;g?$.inverseMat4($.transposeMat4(g,ta),F):$.identityMat4(F,F),function(e,t,i,s,r){function n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}var o,a,l,u,A,c=new Float32Array([0,0,0,0]),h=new Float32Array([0,0,0,0]);for(A=0;Au&&(a=o,u=l),(l=n(h,$o(o=qo(h,"floor","ceil"))))>u&&(a=o,u=l),(l=n(h,$o(o=qo(h,"ceil","ceil"))))>u&&(a=o,u=l),s[r+A+0]=a[0],s[r+A+1]=a[1],s[r+A+2]=0}(F,n,n.length,y.normals,y.normals.length)}if(u)for(var E=0,k=u.length;E0)for(var H=0,V=a.length;H0)for(var j=0,G=l.length;j0){var s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Yo(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=$.mat4());if(e.positionsBuf=new Et(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(var r=0,n=this._portions.length;r0){var u=new Int8Array(i.normals);e.normalsBuf=new Et(t,t.ARRAY_BUFFER,u,i.normals.length,3,t.STATIC_DRAW,!0)}if(i.colors.length>0){var A=new Uint8Array(i.colors);e.colorsBuf=new Et(t,t.ARRAY_BUFFER,A,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.uv.length>0)if(e.uvDecodeMatrix){e.uvBuf=new Et(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,!1)}else{var c=Fi.getUVBounds(i.uv),h=Fi.compressUVs(i.uv,c.min,c.max),d=h.quantized;e.uvDecodeMatrix=$.mat3(h.decodeMatrix),e.uvBuf=new Et(t,t.ARRAY_BUFFER,d,d.length,2,t.STATIC_DRAW,!1)}if(i.metallicRoughness.length>0){var p=new Uint8Array(i.metallicRoughness);e.metallicRoughnessBuf=new Et(t,t.ARRAY_BUFFER,p,i.metallicRoughness.length,2,t.STATIC_DRAW,!1)}if(i.positions.length>0){var f=i.positions.length/3,v=new Float32Array(f);e.flagsBuf=new Et(t,t.ARRAY_BUFFER,v,v.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var g=new Uint8Array(i.pickColors);e.pickColorsBuf=new Et(t,t.ARRAY_BUFFER,g,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var m=new Float32Array(i.offsets);e.offsetsBuf=new Et(t,t.ARRAY_BUFFER,m,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var _=new Uint32Array(i.indices);e.indicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,_,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){var y=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,y,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}}},{key:"isEmpty",value:function(){return!this._state.indicesBuf}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=e,s=this._portions[i],r=4*s.vertsBaseIndex,n=4*s.numVerts,o=this._scratchMemory.getUInt8Array(n),a=t[0],l=t[1],u=t[2],A=t[3],c=0;c3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=e,a=this._portions[o],l=a.vertsBaseIndex,u=a.numVerts,A=l,c=u,h=!!(t&Ne),d=!!(t&Ge),p=!!(t&ze),f=!!(t&Ke),v=!!(t&We),g=!!(t&He),m=!!(t&Qe);r=!h||m||d||p&&!this.model.scene.highlightMaterial.glowThrough||f&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!h||m?so.NOT_RENDERED:f?so.SILHOUETTE_SELECTED:p?so.SILHOUETTE_HIGHLIGHTED:d?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var _=0;_=!h||m?so.NOT_RENDERED:f?so.EDGES_SELECTED:p?so.EDGES_HIGHLIGHTED:d?so.EDGES_XRAYED:v?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED;var y=h&&!m&&g?so.PICK:so.NOT_RENDERED,b=t&Ve?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var B=A,x=A+c;Bg)&&(g=w,s.set(m),r&&$.triangleNormal(d,p,f,r),v=!0)}}return v&&r&&($.transformVec3(this.model.worldNormalMatrix,r,r),$.normalizeVec3(r)),v}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}]),e}(),ca=function(e){g(i,Ao);var t=_(i);function i(e,s){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.edges,o=void 0!==n&&n;return w(this,i),t.call(this,e,s,{instancing:!0,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}]),i}(),ha=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t,i,s=this._scene,r=s._sectionPlanesState,n=s._lightsState,o=r.getNumAllocatedSectionPlanes()>0,a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),s.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),s.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),e=0,t=n.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),o&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),s.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),e=0,t=n.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}]),i}(),da=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=i._lightsState,n=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry flat-shading drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),i.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=s.getNumAllocatedSectionPlanes();a> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var A=0,c=s.getNumAllocatedSectionPlanes();A 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}for(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=r.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),fa=function(e){g(i,ca);var t=_(i);function i(e,s){return w(this,i),t.call(this,e,s,{instancing:!0,edges:!0})}return C(i)}(),va=function(e){g(i,fa);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),ga=function(e){g(i,fa);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),ma=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}]),i}(),_a=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),ya=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),ba=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),Ba=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}]),i}(),xa=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),wa=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Pa={3e3:"linearToLinear",3001:"sRGBToLinear"},Ca=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Instancing geometry quality drawing vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("in vec4 modelNormalMatrixCol0;"),n.push("in vec4 modelNormalMatrixCol1;"),n.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.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);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),r&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),n.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Instancing geometry quality drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=s.lights.length;a0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),o.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),o.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),o.push(" return normalize(surf_norm );"),o.push(" }"),o.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),o.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),o.push(" vec2 st0 = dFdx( uv.st );"),o.push(" vec2 st1 = dFdy( uv.st );"),o.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),o.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),o.push(" vec3 N = normalize( surf_norm );"),o.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),o.push(" mat3 tsn = mat3( S, T, N );"),o.push(" return normalize( tsn * mapN );"),o.push("}"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),s.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Pa[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Pa[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=s.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Fa=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i.gammaOutput,r=i._sectionPlanesState,n=i._lightsState,o=r.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),s&&(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("}")),o){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(var l=0,u=r.getNumAllocatedSectionPlanes();l> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(var c=0,h=r.getNumAllocatedSectionPlanes();c 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=n.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ra=$.vec3(),La=$.vec3(),Ua=$.vec3(),Oa=$.vec3(),Na=$.mat4(),Qa=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Ra;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=La;if(l){var m=$.transformPoint3(A,l,Ua);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,Na),(f=Oa)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ha=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new pa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ma(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new _a(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Ta(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Qa(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new ha(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new ha(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new da(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new da(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new Ca(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Ca(this._scene,!0)),this._pbrRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Fa(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Fa(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pa(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Ba(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new xa(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new va(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ga(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ma(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ya(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ma(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new _a(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new ba(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new wa(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Ta(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Qa(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Va={};var ja=new Uint8Array(4),Ga=new Float32Array(1),za=$.vec4([0,0,0,1]),Ka=new Float32Array(3),Wa=$.vec3(),Xa=$.vec3(),Ja=$.vec3(),Ya=$.vec3(),Za=$.vec3(),qa=$.vec3(),$a=$.vec3(),el=new Float32Array(4),tl=function(){function e(t){var i,s,r;w(this,e),console.info("Creating VBOInstancingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesInstancingLayer"+(t.solid?"-solid":"-surface")+(t.normals?"-normals":"-autoNormals"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Va[s])||(r=new Ha(i),Va[s]=r,r._compile(),r.eagerCreateRenders(),i.on("compile",(function(){r._compile(),r.eagerCreateRenders()})),i.on("destroyed",(function(){delete Va[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new Jt({numInstances:0,obb:$.OBB3(),origin:$.vec3(),geometry:t.geometry,textureSet:t.textureSet,pbrSupported:!1,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&this._state.origin.set(t.origin),this._finalized=!1,this.solid=!!t.solid,this.numIndices=t.geometry.numIndices}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){e.colorsBuf=new Et(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,!1),this._colors=[]}if(this._metallicRoughness.length>0){var o=new Uint8Array(this._metallicRoughness);e.metallicRoughnessBuf=new Et(s,s.ARRAY_BUFFER,o,this._metallicRoughness.length,2,s.STATIC_DRAW,!1)}if(n>0){e.flagsBuf=new Et(s,s.ARRAY_BUFFER,new Float32Array(n),n,1,s.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){e.offsetsBuf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,!1),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){e.positionsBuf=new Et(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,!1),e.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){var a=new Uint8Array(t.colorsCompressed);e.colorsBuf=new Et(s,s.ARRAY_BUFFER,a,a.length,4,s.STATIC_DRAW,!1)}if(t.uvCompressed&&t.uvCompressed.length>0){var l=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Et(s,s.ARRAY_BUFFER,l,l.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Et(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Et(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){var u=!1;e.modelMatrixCol0Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,u),e.modelMatrixCol1Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,u),e.modelMatrixCol2Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,u),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,u),e.modelNormalMatrixCol1Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,u),e.modelNormalMatrixCol2Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,u),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){e.pickColorsBuf=new Et(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,!1),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";ja[0]=t[0],ja[1]=t[1],ja[2]=t[2],ja[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(ja,4*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Ne),r=!!(t&Ge),n=!!(t&ze),o=!!(t&Ke),a=!!(t&We),l=!!(t&He),u=!!(t&Qe),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,A|=(!s||u?so.NOT_RENDERED:o?so.SILHOUETTE_SELECTED:n?so.SILHOUETTE_HIGHLIGHTED:r?so.SILHOUETTE_XRAYED:so.NOT_RENDERED)<<4,A|=(!s||u?so.NOT_RENDERED:o?so.EDGES_SELECTED:n?so.EDGES_HIGHLIGHTED:r?so.EDGES_XRAYED:a?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED)<<8,A|=(s&&!u&&l?so.PICK:so.NOT_RENDERED)<<12,A|=(t&Ve?1:0)<<16,Ga[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(Ga,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ka[0]=t[0],Ka[1]=t[1],Ka[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Ka,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"getEachVertex",value:function(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;var i=this._state,s=i.geometry,r=this._portions[e];if(r)for(var n=s.quantizedPositions,o=i.origin,a=r.offset,l=o[0]+a[0],u=o[1]+a[1],A=o[2]+a[2],c=za,h=r.matrix,d=this.model.sceneModelMatrix,p=i.positionsDecodeMatrix,f=0,v=n.length;fm)&&(m=C,s.set(_),r&&$.triangleNormal(p,f,v,r),g=!0)}}return g&&r&&($.transformVec3(a.normalMatrix,r,r),$.transformVec3(this.model.worldNormalMatrix,r,r),$.normalizeVec3(r)),g}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}]),e}(),il=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}]),i}(),sl=function(e){g(i,il);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),rl=function(e){g(i,il);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),nl=$.vec3(),ol=$.vec3(),al=$.vec3(),ll=$.vec3(),ul=$.mat4(),Al=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=nl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=ol;if(l){var m=al;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,ul),(f=ll)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),cl=$.vec3(),hl=$.vec3(),dl=$.vec3(),pl=$.vec3(),fl=$.mat4(),vl=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=cl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=hl;if(l){var m=dl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,fl),(f=pl)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),gl=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new sl(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new rl(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Al(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new vl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),ml={};var _l=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;w(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]})),yl=function(){function e(t){var i,s,r;w(this,e),console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=ml[s])||(r=new gl(i),ml[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete ml[s],r._destroy()}))),r),this.model=t.model,this._buffer=new _l(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new Jt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var s=new Uint16Array(i.positions);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{var r=Yo(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Et(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.colors.length>0){var o=i.colors.length/4,a=new Float32Array(o);e.flagsBuf=new Et(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var l=new Float32Array(i.offsets);e.offsetsBuf=new Et(t,t.ARRAY_BUFFER,l,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var u=new Uint32Array(i.indices);e.indicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,u,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(r),o=t[0],a=t[1],l=t[2],u=t[3],A=0;A3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=2*e,a=this._portions[o],l=this._portions[o+1],u=a,A=l,c=!!(t&Ne),h=!!(t&Ge),d=!!(t&ze),p=!!(t&Ke),f=!!(t&He),v=!!(t&Qe);r=!c||v||h||d&&!this.model.scene.highlightMaterial.glowThrough||p&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!c||v?so.NOT_RENDERED:p?so.SILHOUETTE_SELECTED:d?so.SILHOUETTE_HIGHLIGHTED:h?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var g=c&&!v&&f?so.PICK:so.NOT_RENDERED,m=t&Ve?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var _=u,y=u+A;_0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):n.push(" outColor = vColor;"),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),xl=function(e){g(i,bl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),wl=$.vec3(),Pl=$.vec3(),Cl=$.vec3();$.vec3();var Ml=$.mat4(),Fl=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.canvas.gl,o=r.camera,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=wl;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Pl;if(l){var g=$.transformPoint3(A,l,Cl);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,Ml),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),El=$.vec3(),kl=$.vec3(),Il=$.vec3();$.vec3();var Dl=$.mat4(),Sl=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=El;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=kl;if(l){var g=$.transformPoint3(A,l,Il);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,Dl),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Tl=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._snapInitRenderer||(this._snapInitRenderer=new Fl(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Sl(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Bl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xl(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Fl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Sl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Rl={};var Ll=new Uint8Array(4),Ul=new Float32Array(1),Ol=new Float32Array(3),Nl=new Float32Array(4),Ql=function(){function e(t){var i,s,r;w(this,e),console.info("VBOInstancingLinesLayer"),this.model=t.model,this.material=t.material,this.sortId="LinesInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Rl[s])||(r=new Tl(i),Rl[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete Rl[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new Jt({obb:$.OBB3(),numInstances:0,origin:null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&(this._state.origin=$.vec3(t.origin)),this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){this._state.colorsBuf=new Et(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,!1),this._colors=[]}if(r>0){this._state.flagsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){this._state.offsetsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){var n=new Uint8Array(i.colorsCompressed);t.colorsBuf=new Et(e,e.ARRAY_BUFFER,n,n.length,4,e.STATIC_DRAW,!1)}if(i.positionsCompressed&&i.positionsCompressed.length>0){t.positionsBuf=new Et(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,!1),t.positionsDecodeMatrix=$.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Et(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){var o=!1;this._state.modelMatrixCol0Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol1Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol2Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,o),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Ll[0]=t[0],Ll[1]=t[1],Ll[2]=t[2],Ll[3]=t[3],this._state.colorsBuf.setData(Ll,4*e,4)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Ne),r=!!(t&Ge),n=!!(t&ze),o=!!(t&Ke),a=!!(t&We),l=!!(t&He),u=!!(t&Qe),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,A|=(!s||u?so.NOT_RENDERED:o?so.SILHOUETTE_SELECTED:n?so.SILHOUETTE_HIGHLIGHTED:r?so.SILHOUETTE_XRAYED:so.NOT_RENDERED)<<4,A|=(!s||u?so.NOT_RENDERED:o?so.EDGES_SELECTED:n?so.EDGES_HIGHLIGHTED:r?so.EDGES_XRAYED:a?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED)<<8,A|=(s&&!u&&l?so.PICK:so.NOT_RENDERED)<<12,A|=(t&Ve?255:0)<<16,Ul[0]=A,this._state.flagsBuf.setData(Ul,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ol[0]=t[0],Ol[1]=t[1],Ol[2]=t[2],this._state.offsetsBuf.setData(Ol,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Nl[0]=t[0],Nl[1]=t[4],Nl[2]=t[8],Nl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Nl,i),Nl[0]=t[1],Nl[1]=t[5],Nl[2]=t[9],Nl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Nl,i),Nl[0]=t[2],Nl[1]=t[6],Nl[2]=t[10],Nl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Nl,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,so.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,so.PICK)}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}]),e}(),Hl=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}]),i}(),Vl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),jl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),r){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}]),i}(),Gl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}]),i}(),zl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),Kl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}]),i}(),Wl=$.vec3(),Xl=$.vec3(),Jl=$.vec3(),Yl=$.vec3(),Zl=$.mat4(),ql=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Wl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Xl;if(l){var m=Jl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,Zl),(f=Yl)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),$l=$.vec3(),eu=$.vec3(),tu=$.vec3(),iu=$.vec3(),su=$.mat4(),ru=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=$l;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=eu;if(l){var m=tu;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,su),(f=iu)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),nu=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Vl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new jl(this._scene)),this._silhouetteRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Gl(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new zl(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Kl(this._scene)),this._occlusionRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new ql(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new ru(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),ou={};var au=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;w(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]})),lu=function(){function e(t){w(this,e),console.info("Creating VBOBatchingPointsLayer"),this.model=t.model,this.sortId="PointsBatchingLayer",this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=ou[t];return i||(i=new nu(e),ou[t]=i,i._compile(),e.on("compile",(function(){i._compile()})),e.on("destroyed",(function(){delete ou[t],i._destroy()}))),i}(t.model.scene),this._buffer=new au(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new Jt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var s=new Uint16Array(i.positions);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{var r=Yo(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Et(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.STATIC_DRAW,!1)}if(i.positions.length>0){var o=i.positions.length/3,a=new Float32Array(o);e.flagsBuf=new Et(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var l=new Uint8Array(i.pickColors);e.pickColorsBuf=new Et(t,t.ARRAY_BUFFER,l,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var u=new Float32Array(i.offsets);e.offsetsBuf=new Et(t,t.ARRAY_BUFFER,u,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized"}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(r),o=t[0],a=t[1],l=t[2],u=0;u0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),cu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),hu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}]),i}(),du=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),pu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),fu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),r){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return n.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),vu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),gu=$.vec3(),mu=$.vec3(),_u=$.vec3();$.vec3();var yu=$.mat4(),bu=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.canvas.gl,o=r.camera,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=gu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=mu;if(l){var g=$.transformPoint3(A,l,_u);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,yu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Bu=$.vec3(),xu=$.vec3(),wu=$.vec3();$.vec3();var Pu=$.mat4(),Cu=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=Bu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=xu;if(l){var g=$.transformPoint3(A,l,wu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,Pu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Mu=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Au(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new cu(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new fu(this._scene)),this._depthRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new hu(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new du(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new pu(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new vu(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new bu(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Cu(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Fu={};var Eu=new Uint8Array(4),ku=new Float32Array(1),Iu=new Float32Array(3),Du=new Float32Array(4),Su=function(){function e(t){var i,s,r;w(this,e),console.info("VBOInstancingPointsLayer"),this.model=t.model,this.material=t.material,this.sortId="PointsInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Fu[s])||(r=new Mu(i),Fu[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete Fu[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new Jt({obb:$.OBB3(),numInstances:0,origin:t.origin?$.vec3(t.origin):null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){i.flagsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){i.offsetsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){i.positionsBuf=new Et(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,!1),i.positionsDecodeMatrix=$.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){var r=new Uint8Array(s.colorsCompressed);i.colorsBuf=new Et(e,e.ARRAY_BUFFER,r,r.length,4,e.STATIC_DRAW,!1)}if(this._modelMatrixCol0.length>0){var n=!1;i.modelMatrixCol0Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,n),i.modelMatrixCol1Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,n),i.modelMatrixCol2Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,n),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){i.pickColorsBuf=new Et(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,!1),this._pickColors=[]}i.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Eu[0]=t[0],Eu[1]=t[1],Eu[2]=t[2],this._state.colorsBuf.setData(Eu,3*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Ne),r=!!(t&Ge),n=!!(t&ze),o=!!(t&Ke),a=!!(t&We),l=!!(t&He),u=!!(t&Qe),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,A|=(!s||u?so.NOT_RENDERED:o?so.SILHOUETTE_SELECTED:n?so.SILHOUETTE_HIGHLIGHTED:r?so.SILHOUETTE_XRAYED:so.NOT_RENDERED)<<4,A|=(!s||u?so.NOT_RENDERED:o?so.EDGES_SELECTED:n?so.EDGES_HIGHLIGHTED:r?so.EDGES_XRAYED:a?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED)<<8,A|=(s&&!u&&l?so.PICK:so.NOT_RENDERED)<<12,A|=(t&Ve?255:0)<<16,ku[0]=A,this._state.flagsBuf.setData(ku,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Iu[0]=t[0],Iu[1]=t[1],Iu[2]=t[2],this._state.offsetsBuf.setData(Iu,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Du[0]=t[0],Du[1]=t[4],Du[2]=t[8],Du[3]=t[12],this._state.modelMatrixCol0Buf.setData(Du,i),Du[0]=t[1],Du[1]=t[5],Du[2]=t[9],Du[3]=t[13],this._state.modelMatrixCol1Buf.setData(Du,i),Du[0]=t[2],Du[1]=t[6],Du[2]=t[10],Du[3]=t[14],this._state.modelMatrixCol2Buf.setData(Du,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,so.PICK)}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,so.PICK)}},{key:"drawPickNormals",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,so.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,so.PICK)}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}]),e}(),Tu=$.vec3(),Ru=$.vec3(),Lu=$.mat4(),Uu=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=r.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=Tu;if(f){var m=$.transformPoint3(c,u,Ru);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Te(d,g,Lu)}else p=d;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),o.drawArrays(o.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),o.drawArrays(o.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),o.drawArrays(o.LINES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ou=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}},{key:"eagerCreateRenders",value:function(){}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Uu(this._scene,!1)),this._colorRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy()}}]),e}(),Nu={};var Qu=C((function e(){w(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]})),Hu=function(){function e(){w(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}},{key:"bindLineIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}]),e}(),Vu=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;w(this,e),this._gl=t,this._texture=i,this._textureWidth=s,this._textureHeight=r,this._textureData=n}return C(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),ju={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(ju,null,4));var e=0;Object.keys(ju).forEach((function(t){t.startsWith("size")&&(e+=ju[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/ju.totalLines).toFixed(2)));var t={};Object.keys(ju).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((ju[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var Gu=function(){function e(){w(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,s,r){var n=t.length;this.numPortions=n;var o=4096,a=Math.ceil(n/512);if(0===a)throw"texture height===0";var l=new Uint8Array(16384*a);ju.sizeDataColorsAndFlags+=l.byteLength,ju.numberOfTextures++;for(var u=0;u>24&255,s[u]>>16&255,s[u]>>8&255,255&s[u]],32*u+16),l.set([r[u]>>24&255,r[u]>>16&255,r[u]>>8&255,255&r[u]],32*u+20);var A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,A,o,a,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";var r=new Float32Array(1536*s).fill(0);ju.sizeDataTextureOffsets+=r.byteLength,ju.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,n,i,s,r)}},{key:"generateTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var s=2048,r=Math.ceil(i/512),n=new Float32Array(8192*r);ju.numberOfTextures++;for(var o=0;o65536&&ju.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[s]){var r=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/2})),(this._state.numVertices+n>4096*Ku||r+o>4096*Ku)&&ju.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*Ku&&r+o<=4096*Ku)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var s=[];t.buckets.forEach((function(e,r){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(r):"".concat(t.id,"#").concat(r),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);s.push(a)}));var r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/2/8)*2;ju.overheadSizeAlignementIndices+=2*(i-t.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(t.indices),t.indices=s}var r=t.positionsCompressed,n=t.indices,o=this._buffer;o.positionsCompressed.push(r);var a,l=o.lenPositionsCompressed/3,u=r.length/3;o.lenPositionsCompressed+=r.length;var A,c=0;n&&(c=n.length/2,u<=256?(A=o.indices8Bits,a=o.lenIndices8Bits/2,o.lenIndices8Bits+=n.length):u<=65536?(A=o.indices16Bits,a=o.lenIndices16Bits/2,o.lenIndices16Bits+=n.length):(A=o.indices32Bits,a=o.lenIndices32Bits/2,o.lenIndices32Bits+=n.length),A.push(n));return this._state.numVertices+=u,ju.numberOfGeometries++,{vertexBase:l,numVertices:u,numLines:c,indicesBase:a}}},{key:"_createSubPortion",value:function(e,t){var i,s=e.color,r=e.colors,n=e.opacity,o=e.meshMatrix,a=e.pickColor,l=this._buffer,u=this._state;l.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),l.perObjectInstancePositioningMatrices.push(o||Zu),l.perObjectSolid.push(!!e.solid),r?l.perObjectColors.push([255*r[0],255*r[1],255*r[2],255]):s&&l.perObjectColors.push([s[0],s[1],s[2],n]),l.perObjectPickColors.push(a),l.perObjectVertexBases.push(t.vertexBase),i=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,l.perObjectIndexBaseOffsets.push(i/2-t.indicesBase);var A=this._subPortions.length;if(t.numLines>0){var c,h=2*t.numLines;t.numVertices<=256?(c=l.perLineNumberPortionId8Bits,u.numIndices8Bits+=h,ju.totalLines8Bits+=t.numLines):t.numVertices<=65536?(c=l.perLineNumberPortionId16Bits,u.numIndices16Bits+=h,ju.totalLines16Bits+=t.numLines):(c=l.perLineNumberPortionId32Bits,u.numIndices32Bits+=h,ju.totalLines32Bits+=t.numLines),ju.totalLines+=t.numLines;for(var d=0;d0&&(i.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,r.indices8Bits,r.lenIndices8Bits)),r.lenIndices16Bits>0&&(i.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,r.indices16Bits,r.lenIndices16Bits)),r.lenIndices32Bits>0&&(i.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,r.indices32Bits,r.lenIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Xu))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=this._portionToSubPortionsMap[e],n=0,o=r.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=!!(t&Ne),a=!!(t&Ge),l=!!(t&ze),u=!!(t&Ke),A=!!(t&He),c=!!(t&Qe);r=!o||c||a?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!o||c?so.NOT_RENDERED:u?so.SILHOUETTE_SELECTED:l?so.SILHOUETTE_HIGHLIGHTED:a?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var h=o&&!c&&A?so.PICK:so.NOT_RENDERED,d=this._dataTextureState,p=this.model.scene.canvas.gl;Xu[0]=r,Xu[1]=n,Xu[3]=h,d.texturePerObjectColorsAndFlags._textureData.set(Xu,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,Xu))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=this._portionToSubPortionsMap[e],r=0,n=s.length;r2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var s=t&Ve?255:0,r=this._dataTextureState,n=this.model.scene.canvas.gl;Xu[0]=s,Xu[1]=0,Xu[2]=1,Xu[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(Xu,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,Xu))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Ju))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Wu))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){}},{key:"drawSilhouetteHighlighted",value:function(e,t){}},{key:"drawSilhouetteSelected",value:function(e,t){}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){}},{key:"drawSnap",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),$u=$.vec3(),eA=$.vec3(),tA=$.vec3();$.vec3();var iA=$.vec4(),sA=$.mat4(),rA=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=$u;if(f){var m=$.transformPoint3(c,u,eA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Te(r.viewMatrix,g,sA),(p=tA)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ft(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n0,n=[];n.push("#version 300 es"),n.push("// TrianglesDataTextureColorRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=s.lights.length;l0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),nA=new Float32Array([1,1,1]),oA=$.vec3(),aA=$.vec3(),lA=$.vec3();$.vec3();var uA=$.mat4(),AA=function(){function e(t,i){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=r.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=oA;if(u){var g=aA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Te(d,v,uA),(f=lA)[0]=r.eye[0]-v[0],f[1]=r.eye[1]-v[1],f[2]=r.eye[2]-v[2]}else p=d,f=r.eye;if(o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===so.SILHOUETTE_XRAYED){var m=s.xrayMaterial._state,_=m.fillColor,y=m.fillAlpha;o.uniform4f(this._uColor,_[0],_[1],_[2],y)}else if(i===so.SILHOUETTE_HIGHLIGHTED){var b=s.highlightMaterial._state,B=b.fillColor,x=b.fillAlpha;o.uniform4f(this._uColor,B[0],B[1],B[2],x)}else if(i===so.SILHOUETTE_SELECTED){var w=s.selectedMaterial._state,P=w.fillColor,C=w.fillAlpha;o.uniform4f(this._uColor,P[0],P[1],P[2],C)}else o.uniform4fv(this._uColor,nA);if(s.logarithmicDepthBufferEnabled){var M=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,M)}var F=s._sectionPlanesState.getNumAllocatedSectionPlanes(),E=s._sectionPlanesState.sectionPlanes.length;if(F>0)for(var k=s._sectionPlanesState.sectionPlanes,I=t.layerIndex*E,D=n.renderFlags,S=0;S0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),cA=new Float32Array([0,0,0,1]),hA=$.vec3(),dA=$.vec3();$.vec3();var pA=$.mat4(),fA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=hA;if(f){var m=$.transformPoint3(c,u,dA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Te(d,g,pA)}else p=d;if(o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),i===so.EDGES_XRAYED){var _=r.xrayMaterial._state,y=_.edgeColor,b=_.edgeAlpha;o.uniform4f(this._uColor,y[0],y[1],y[2],b)}else if(i===so.EDGES_HIGHLIGHTED){var B=r.highlightMaterial._state,x=B.edgeColor,w=B.edgeAlpha;o.uniform4f(this._uColor,x[0],x[1],x[2],w)}else if(i===so.EDGES_SELECTED){var P=r.selectedMaterial._state,C=P.edgeColor,M=P.edgeAlpha;o.uniform4f(this._uColor,C[0],C[1],C[2],M)}else o.uniform4fv(this._uColor,cA);var F=r._sectionPlanesState.getNumAllocatedSectionPlanes(),E=r._sectionPlanesState.sectionPlanes.length;if(F>0)for(var k=r._sectionPlanesState.sectionPlanes,I=t.layerIndex*E,D=s.renderFlags,S=0;S0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),vA=$.vec3(),gA=$.vec3(),mA=$.mat4(),_A=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=vA;if(f){var m=$.transformPoint3(c,u,gA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Te(d,g,mA)}else p=d;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*y,x=s.renderFlags,w=0;w<_;w++){var P=this._uSectionPlanes[w];if(P)if(w0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),yA=$.vec3(),bA=$.vec3(),BA=$.vec3(),xA=$.mat4(),wA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate;A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==c[0]||0!==c[1]||0!==c[2],v=0!==h[0]||0!==h[1]||0!==h[2];if(f||v){var g=yA;if(f){var m=$.transformPoint3(d,c,bA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=h[0],g[1]+=h[1],g[2]+=h[2],s=Te(a.viewMatrix,g,xA),(r=BA)[0]=a.eye[0]-g[0],r[1]=a.eye[1]-g[1],r[2]=a.eye[2]-g[2]}else s=a.viewMatrix,r=a.eye;if(l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),l.uniform3fv(this._uCameraEyeRtc,r),l.uniform1i(this._uRenderPass,i),o.logarithmicDepthBufferEnabled){var _=2/(Math.log(a.project.far+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,_)}var y=o._sectionPlanesState.getNumAllocatedSectionPlanes(),b=o._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=o._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),PA=$.vec3(),CA=$.vec3(),MA=$.vec3();$.vec3();var FA=$.mat4(),EA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=e.pickViewMatrix||a.viewMatrix;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==h[0]||0!==h[1]||0!==h[2]){var v=PA;if(c){var g=CA;$.transformPoint3(d,c,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=h[0],v[1]+=h[1],v[2]+=h[2],s=Te(f,v,FA),(r=MA)[0]=a.eye[0]-v[0],r[1]=a.eye[1]-v[1],r[2]=a.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else s=f,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(l.uniform3fv(this._uCameraEyeRtc,r),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniform1f(this._uPickZNear,e.pickZNear),l.uniform1f(this._uPickZFar,e.pickZFar),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),o.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,m)}var _=o._sectionPlanesState.getNumAllocatedSectionPlanes(),y=o._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=o._sectionPlanesState.sectionPlanes,B=t.layerIndex*y,x=n.renderFlags,w=0;w<_;w++){var P=this._uSectionPlanes[w];if(P)if(w0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),kA=$.vec3(),IA=$.vec3(),DA=$.vec3(),SA=$.vec3();$.vec3();var TA=$.mat4(),RA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=kA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=IA;if(m){var b=$.transformPoint3(d,c,DA);y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],s=Te(v,y,TA),(r=SA)[0]=a.eye[0]-y[0],r[1]=a.eye[1]-y[1],r[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else s=v,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,r),l.uniform2fv(this.uVectorA,e.snapVectorA),l.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var B=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,B);var x=o._sectionPlanesState.getNumAllocatedSectionPlanes(),w=o._sectionPlanesState.sectionPlanes.length;if(x>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*w,M=n.renderFlags,F=0;F0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),l.drawArrays(S,0,u.numEdgeIndices8Bits)),u.numEdgeIndices16Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),l.drawArrays(S,0,u.numEdgeIndices16Bits)),u.numEdgeIndices32Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),l.drawArrays(S,0,u.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),LA=$.vec3(),UA=$.vec3(),OA=$.vec3(),NA=$.vec3();$.vec3();var QA=$.mat4(),HA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=LA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=UA;if(m){var b=OA;$.transformPoint3(d,c,b),y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],s=Te(v,y,QA),(r=NA)[0]=a.eye[0]-y[0],r[1]=a.eye[1]-y[1],r[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else s=v,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,r),l.uniform2fv(this._uVectorA,e.snapVectorA),l.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var B=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,B);var x=o._sectionPlanesState.getNumAllocatedSectionPlanes(),w=o._sectionPlanesState.sectionPlanes.length;if(x>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*w,M=n.renderFlags,F=0;F0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),VA=$.vec3(),jA=$.vec3(),GA=$.vec3();$.vec3();var zA=$.mat4(),KA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=e.pickViewMatrix||n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=VA;if(u){var g=jA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Te(d,v,zA),(f=GA)[0]=n.eye[0]-v[0],f[1]=n.eye[1]-v[1],f[2]=n.eye[2]-v[2]}else p=d,f=n.eye;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0)for(var y=r._sectionPlanesState.sectionPlanes,b=t.layerIndex*_,B=s.renderFlags,x=0;x0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),WA=$.vec3(),XA=$.vec3(),JA=$.vec3();$.vec3();var YA=$.mat4(),ZA=function(){function e(t){w(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=WA;if(f){var m=$.transformPoint3(c,u,XA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Te(r.viewMatrix,g,YA),(p=JA)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),qA=$.vec3(),$A=$.vec3(),ec=$.vec3();$.vec3();var tc=$.mat4(),ic=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));var f=0!==l[0]||0!==l[1]||0!==l[2],v=0!==u[0]||0!==u[1]||0!==u[2];if(f||v){var g=qA;if(f){var m=$A;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],d=Te(h,g,tc),(p=ec)[0]=n.eye[0]-g[0],p[1]=n.eye[1]-g[1],p[2]=n.eye[2]-g[2]}else d=h,p=n.eye;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,c),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*y,x=s.renderFlags,w=0;w<_;w++){var P=this._uSectionPlanes[w];if(P)if(w0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&mt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),mt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(mt.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&mt.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&&mt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&mt.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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),sc=$.vec3(),rc=$.vec3(),nc=$.vec3();$.vec3(),$.vec4();var oc=$.mat4(),ac=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=sc;if(f){var m=$.transformPoint3(c,u,rc);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Te(r.viewMatrix,g,oc),(p=nc)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniform2fv(this._uPickClipPos,e.pickClipPos),o.uniform2f(this._uDrawingBufferSize,o.drawingBufferWidth,o.drawingBufferHeight),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),lc=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new AA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new EA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new ac(this._scene)),this._snapRenderer||(this._snapRenderer=new RA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new HA(this._scene)),this._snapRenderer||(this._snapRenderer=new RA(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new rA(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new rA(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new AA(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new ZA(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new ic(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new fA(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new _A(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wA(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ac(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new ac(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new EA(this._scene)),this._pickDepthRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new RA(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new HA(this._scene)),this._snapInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new KA(this._scene)),this._occlusionRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}]),e}(),uc={};var Ac=C((function e(){w(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),cc=function(){function e(){w(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}]),e}(),hc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(hc,null,4));var e=0;Object.keys(hc).forEach((function(t){t.startsWith("size")&&(e+=hc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/hc.totalPolygons).toFixed(2)));var t={};Object.keys(hc).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((hc[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var dc=function(){function e(){w(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"createTextureForColorsAndFlags",value:function(e,t,i,s,r,n,o){var a=t.length;this.numPortions=a;var l=4096,u=Math.ceil(a/512);if(0===u)throw"texture height===0";var A=new Uint8Array(16384*u);hc.sizeDataColorsAndFlags+=A.byteLength,hc.numberOfTextures++;for(var c=0;c>24&255,s[c]>>16&255,s[c]>>8&255,255&s[c]],32*c+16),A.set([r[c]>>24&255,r[c]>>16&255,r[c]>>8&255,255&r[c]],32*c+20),A.set([n[c]>>24&255,n[c]>>16&255,n[c]>>8&255,255&n[c]],32*c+24),A.set([o[c]?1:0,0,0,0],32*c+28);var h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,A,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,h,l,u,A)}},{key:"createTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";var r=new Float32Array(1536*s).fill(0);hc.sizeDataTextureOffsets+=r.byteLength,hc.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,n,i,s,r)}},{key:"createTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var s=2048,r=Math.ceil(i/512),n=new Float32Array(8192*r);hc.numberOfTextures++;for(var o=0;o65536&&hc.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[s]){var r=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/3})),(this._state.numVertices+n>4096*fc||r+o>4096*fc)&&hc.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*fc&&r+o<=4096*fc)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var s=[];t.buckets.forEach((function(e,r){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(r):"".concat(t.id,"#").concat(r),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);s.push(a)}));var r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/3/8)*3;hc.overheadSizeAlignementIndices+=2*(i-t.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){var r=8*Math.ceil(t.edgeIndices.length/2/8)*2;hc.overheadSizeAlignementEdgeIndices+=2*(r-t.edgeIndices.length);var n=new Uint32Array(r);n.fill(0),n.set(t.edgeIndices),t.edgeIndices=n}var o=t.positionsCompressed,a=t.indices,l=t.edgeIndices,u=this._buffer;u.positionsCompressed.push(o);var A,c=u.lenPositionsCompressed/3,h=o.length/3;u.lenPositionsCompressed+=o.length;var d,p,f=0;a&&(f=a.length/3,h<=256?(d=u.indices8Bits,A=u.lenIndices8Bits/3,u.lenIndices8Bits+=a.length):h<=65536?(d=u.indices16Bits,A=u.lenIndices16Bits/3,u.lenIndices16Bits+=a.length):(d=u.indices32Bits,A=u.lenIndices32Bits/3,u.lenIndices32Bits+=a.length),d.push(a));var v,g=0;l&&(g=l.length/2,h<=256?(v=u.edgeIndices8Bits,p=u.lenEdgeIndices8Bits/2,u.lenEdgeIndices8Bits+=l.length):h<=65536?(v=u.edgeIndices16Bits,p=u.lenEdgeIndices16Bits/2,u.lenEdgeIndices16Bits+=l.length):(v=u.edgeIndices32Bits,p=u.lenEdgeIndices32Bits/2,u.lenEdgeIndices32Bits+=l.length),v.push(l));return this._state.numVertices+=h,hc.numberOfGeometries++,{vertexBase:c,numVertices:h,numTriangles:f,numEdges:g,indicesBase:A,edgeIndicesBase:p}}},{key:"_createSubPortion",value:function(e,t,i,s){var r=e.color;e.metallic,e.roughness;var n,o,a=e.colors,l=e.opacity,u=e.meshMatrix,A=e.pickColor,c=this._buffer,h=this._state;c.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),c.perObjectInstancePositioningMatrices.push(u||yc),c.perObjectSolid.push(!!e.solid),a?c.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):r&&c.perObjectColors.push([r[0],r[1],r[2],l]),c.perObjectPickColors.push(A),c.perObjectVertexBases.push(t.vertexBase),n=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,c.perObjectIndexBaseOffsets.push(n/3-t.indicesBase),o=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,c.perObjectEdgeIndexBaseOffsets.push(o/2-t.edgeIndicesBase);var d=this._subPortions.length;if(t.numTriangles>0){var p,f=3*t.numTriangles;t.numVertices<=256?(p=c.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=f,hc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(p=c.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=f,hc.totalPolygons16Bits+=t.numTriangles):(p=c.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=f,hc.totalPolygons32Bits+=t.numTriangles),hc.totalPolygons+=t.numTriangles;for(var v=0;v0){var g,m=2*t.numEdges;t.numVertices<=256?(g=c.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=m,hc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=c.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=m,hc.totalEdges16Bits+=t.numEdges):(g=c.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=m,hc.totalEdges32Bits+=t.numEdges),hc.totalEdges+=t.numEdges;for(var _=0;_0&&(i.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId8Bits)),r.perEdgeNumberPortionId16Bits.length>0&&(i.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId16Bits)),r.perEdgeNumberPortionId32Bits.length>0&&(i.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId32Bits)),r.lenIndices8Bits>0&&(i.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(s,r.indices8Bits,r.lenIndices8Bits)),r.lenIndices16Bits>0&&(i.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(s,r.indices16Bits,r.lenIndices16Bits)),r.lenIndices32Bits>0&&(i.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(s,r.indices32Bits,r.lenIndices32Bits)),r.lenEdgeIndices8Bits>0&&(i.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(s,r.edgeIndices8Bits,r.lenEdgeIndices8Bits)),r.lenEdgeIndices16Bits>0&&(i.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(s,r.edgeIndices16Bits,r.lenEdgeIndices16Bits)),r.lenEdgeIndices32Bits>0&&(i.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(s,r.edgeIndices32Bits,r.lenEdgeIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,gc)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=this._portionToSubPortionsMap[e],n=0,o=r.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=!!(t&Ne),a=!!(t&Ge),l=!!(t&ze),u=!!(t&Ke),A=!!(t&We),c=!!(t&He),h=!!(t&Qe);r=!o||h||a?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!o||h?so.NOT_RENDERED:u?so.SILHOUETTE_SELECTED:l?so.SILHOUETTE_HIGHLIGHTED:a?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var d=0;d=!o||h?so.NOT_RENDERED:u?so.EDGES_SELECTED:l?so.EDGES_HIGHLIGHTED:a?so.EDGES_XRAYED:A?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED;var p=o&&!h&&c?so.PICK:so.NOT_RENDERED,f=this._dtxState,v=this.model.scene.canvas.gl;gc[0]=r,gc[1]=n,gc[2]=d,gc[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(gc,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),v.bindTexture(v.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),v.texSubImage2D(v.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,v.RGBA_INTEGER,v.UNSIGNED_BYTE,gc))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=this._portionToSubPortionsMap[e],r=0,n=s.length;r2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var s=t&Ve?255:0,r=this._dtxState,n=this.model.scene.canvas.gl;gc[0]=s,gc[1]=0,gc[2]=1,gc[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(gc,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,gc))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,mc))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,vc))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,so.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){var i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){var s=t.gl;i?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),t.backfaces=i}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,so.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,so.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,so.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,so.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,so.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,so.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,so.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,so.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,so.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,so.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),Bc=function(){function e(t){w(this,e),this.id=t.id,this.colorTexture=t.colorTexture,this.metallicRoughnessTexture=t.metallicRoughnessTexture,this.normalsTexture=t.normalsTexture,this.emissiveTexture=t.emissiveTexture,this.occlusionTexture=t.occlusionTexture}return C(e,[{key:"destroy",value:function(){}}]),e}(),xc=function(){function e(t){w(this,e),this.id=t.id,this.texture=t.texture}return C(e,[{key:"destroy",value:function(){this.texture&&(this.texture.destroy(),this.texture=null)}}]),e}(),wc={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}},Pc=function(){function e(t,i,s){w(this,e),this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=t,this.onProgress=i,this.onError=s}return C(e,[{key:"itemStart",value:function(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}},{key:"itemEnd",value:function(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}},{key:"itemError",value:function(e){void 0!==this.onError&&this.onError(e)}},{key:"resolveURL",value:function(e){return this.urlModifier?this.urlModifier(e):e}},{key:"setURLModifier",value:function(e){return this.urlModifier=e,this}},{key:"addHandler",value:function(e,t){return this.handlers.push(e,t),this}},{key:"removeHandler",value:function(e){var t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}},{key:"getHandler",value:function(e){for(var t=0,i=this.handlers.length;t0&&void 0!==arguments[0]?arguments[0]:4;w(this,e),this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}return C(e,[{key:"_initWorker",value:function(e){if(!this.workers[e]){var t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}},{key:"_getIdleWorker",value:function(){for(var e=0;e0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Ic++}return this._transcoderPending}},{key:"transcode",value:function(e,t){var i=this,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise((function(r,n){var o=s;i._init().then((function(){return i._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e)})).then((function(e){var i=e.data,s=i.mipmaps,o=(i.width,i.height,i.format),a=i.type,l=i.error,u=i.dfdTransferFn,A=i.dfdFlags;if("error"===a)return n(l);t.setCompressedData({mipmaps:s,props:{format:o,minFilter:1===s.length?1006:1008,magFilter:1===s.length?1006:1008,encoding:2===u?3001:3e3,premultiplyAlpha:!!(1&A)}}),r()}))}))}},{key:"destroy",value:function(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Ic--}}]),e}();Dc.BasisFormat={ETC1S:0,UASTC_4x4:1},Dc.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},Dc.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},Dc.BasisWorker=function(){var e,t,i,s=_EngineFormat,r=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",(function(o){var A,c=o.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((function(e){i={wasmBinary:A,onRuntimeInitialized:e},BASIS(i)})).then((function(){i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((function(){try{for(var t=function(t){var o=new i.KTX2File(new Uint8Array(t));function A(){o.close(),o.delete()}if(!o.isValid())throw A(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");var c=o.isUASTC()?n.UASTC_4x4:n.ETC1S,h=o.getWidth(),d=o.getHeight(),p=o.getLevels(),f=o.getHasAlpha(),v=o.getDFDTransferFunc(),g=o.getDFDFlags(),m=function(t,i,o,A){for(var c,h,d=t===n.ETC1S?a:l,p=0;p=0;--r){var n=this.tryEntries[r],o=n.completion;if("root"===n.tryLoc)return s("end");if(n.tryLoc<=this.prev){var a=i.call(n,"catchLoc"),l=i.call(n,"finallyLoc");if(a&&l){if(this.prev=0;--s){var r=this.tryEntries[s];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),w(i),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var s=i.completion;if("throw"===s.type){var r=s.arg;w(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),c}},e}function l(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function u(e){return function(){var t=this,i=arguments;return new Promise((function(s,r){var n=e.apply(t,i);function o(e){l(n,s,r,o,a,"next",e)}function a(e){l(n,s,r,o,a,"throw",e)}o(void 0)}))}}function A(e){return function(e){if(Array.isArray(e))return p(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=d(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var s=0,r=function(){};return{s:r,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw n}}}}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var s,r,n=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(s=i.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return n}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e,t){if(e){if("string"==typeof e)return p(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=new Array(t);i0&&void 0!==arguments[0]?arguments[0]:{};w(this,e),this._id=H.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==i.hideOnMouseDown&&(document.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),i.items&&(this.items=i.items),this._hideOnAction=!1!==i.hideOnAction,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return C(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var s=0,r=i.length;s0,A=t._getNextId(),c=n.getTitle||function(){return n.title||""},h=n.doAction||n.callback||function(){},d=n.getEnabled||function(){return!0},p=n.getShown||function(){return!0},f=new G(A,c,h,d,p);if(f.parentMenu=r,l.items.push(f),u){var v=e(o);f.subMenu=v,v.parentItem=f}t._itemList.push(f),t._itemMap[f.id]=f},A=0,c=a.length;A'),s.push("
    "),i)for(var r=0,n=i.length;r'+d+" [MORE]"):s.push('
  • '+d+"
  • ")}}s.push("
"),s.push("");var p=s.join("");document.body.insertAdjacentHTML("beforeend",p);var f=document.querySelector("."+e.id);e.menuElement=f,f.style["border-radius"]="4px",f.style.display="none",f.style["z-index"]=3e5,f.style.background="white",f.style.border="1px solid black",f.style["box-shadow"]="0 4px 5px 0 gray",f.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var m=0,_=i.length;m<_;m++){var y=i[m].items;if(y)for(var b=function(e,i){var s=y[e],r=s.subMenu;if(s.itemElement=document.getElementById(s.id),!s.itemElement)return console.error("ContextMenu item element not found: "+s.id),"continue";s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=s.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==s.enabled){var i=s.itemElement,r=t.menuElement,n=i.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?v._showMenu(t.id,n.left-200,n.top-1):v._showMenu(t.id,n.right-5,n.top-1),g=t}}else g&&(v._hideMenu(g.id),g=null)})),r||(s.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==s.enabled&&(s.doAction&&s.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==s.enabled&&s.doHover&&s.doHover(v._context)})))},B=0,x=y.length;Bwindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),K=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this.viewer=t,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=s.zoomLevel||2,this._active=!1!==s.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(function(){i._active&&i._visible&&i.update()}))}return C(e,[{key:"update",value:function(){if(this._active&&this._visible&&this._canvasPos){var e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop="".concat(t.bottom-t.top-this._lensCanvas.height-85,"px"):this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);var s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);var r=[(e.left+e.right)/2,(e.top+e.bottom)/2];if(this._snappedCanvasPos){var n=this._snappedCanvasPos[0]-this._canvasPos[0],o=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft="".concat(r[0]+n*this._zoomLevel-10,"px"),this._lensCursorDiv.style.marginTop="".concat(r[1]+o*this._zoomLevel-10,"px")}else this._lensCursorDiv.style.marginLeft="".concat(r[0]-10,"px"),this._lensCursorDiv.style.marginTop="".concat(r[1]-10,"px")}}},{key:"zoomFactor",get:function(){return this._zoomFactor},set:function(e){this._zoomFactor=e,this.update()}},{key:"canvasPos",get:function(){return this._canvasPos},set:function(e){this._canvasPos=e,this.update()}},{key:"snappedCanvasPos",get:function(){return this._snappedCanvasPos},set:function(e){this._snappedCanvasPos=e,this.update()}},{key:"snapped",get:function(){return this._snapped},set:function(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}},{key:"active",get:function(){return this._active},set:function(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"destroy",value:function(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}]),e}(),W=!0,X=W?Float64Array:Float32Array,J=new X(3),Y=new X(16),Z=new X(16),q=new X(4),$={setDoublePrecisionEnabled:function(e){X=(W=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return W},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new X(e||2)},vec3:function(e){return new X(e||3)},vec4:function(e){return new X(e||4)},mat3:function(e){return new X(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new X(16);return 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:function(e){return new X(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,i){for(var s=new X(2),r=0,n=e.length;r>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&s|128]).concat(e[s>>8&255],"-").concat(e[s>>16&255]).concat(e[s>>24&255]).concat(e[255&r]).concat(e[r>>8&255]).concat(e[r>>16&255]).concat(e[r>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,e))},fmod:function(e,t){if(e1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new X(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=$.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=$.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=$.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,s=(t=Array.prototype.slice.call(t)).length;i0&&void 0!==arguments[0]?arguments[0]:new X(16);return 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:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new X(9);return 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:function(e){return 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:function(e,t){return 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:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return $.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],u=e[6],A=e[7],c=e[8],h=e[9],d=e[10],p=e[11],f=e[12],v=e[13],g=e[14],m=e[15],_=t[0],y=t[1],b=t[2],B=t[3],x=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],k=t[11],I=t[12],D=t[13],S=t[14],T=t[15];return i[0]=_*s+y*a+b*c+B*f,i[1]=_*r+y*l+b*h+B*v,i[2]=_*n+y*u+b*d+B*g,i[3]=_*o+y*A+b*p+B*m,i[4]=x*s+w*a+P*c+C*f,i[5]=x*r+w*l+P*h+C*v,i[6]=x*n+w*u+P*d+C*g,i[7]=x*o+w*A+P*p+C*m,i[8]=M*s+F*a+E*c+k*f,i[9]=M*r+F*l+E*h+k*v,i[10]=M*n+F*u+E*d+k*g,i[11]=M*o+F*A+E*p+k*m,i[12]=I*s+D*a+S*c+T*f,i[13]=I*r+D*l+S*h+T*v,i[14]=I*n+D*u+S*d+T*g,i[15]=I*o+D*A+S*p+T*m,i},mulMat3:function(e,t,i){i||(i=new X(9));var s=e[0],r=e[3],n=e[6],o=e[1],a=e[4],l=e[7],u=e[2],A=e[5],c=e[8],h=t[0],d=t[3],p=t[6],f=t[1],v=t[4],g=t[7],m=t[2],_=t[5],y=t[8];return i[0]=s*h+r*f+n*m,i[3]=s*d+r*v+n*_,i[6]=s*p+r*g+n*y,i[1]=o*h+a*f+l*m,i[4]=o*d+a*v+l*_,i[7]=o*p+a*g+l*y,i[2]=u*h+A*f+c*m,i[5]=u*d+A*v+c*_,i[8]=u*p+A*g+c*y,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=t[0],r=t[1],n=t[2],o=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],s=e[14],r=e[8],n=e[13],o=e[12],a=e[9];if(!t||e===t){var l=e[1],u=e[2],A=e[3],c=e[6],h=e[7],d=e[11];return e[1]=i,e[2]=r,e[3]=o,e[4]=l,e[6]=a,e[7]=n,e[8]=u,e[9]=c,e[11]=s,e[12]=A,e[13]=h,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],u=e[8],A=e[9],c=e[10],h=e[11],d=e[12],p=e[13],f=e[14],v=e[15];return d*A*a*r-u*p*a*r-d*o*c*r+n*p*c*r+u*o*f*r-n*A*f*r-d*A*s*l+u*p*s*l+d*i*c*l-t*p*c*l-u*i*f*l+t*A*f*l+d*o*s*h-n*p*s*h-d*i*a*h+t*p*a*h+n*i*f*h-t*o*f*h-u*o*s*v+n*A*s*v+u*i*a*v-t*A*a*v-n*i*c*v+t*o*c*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],l=e[6],u=e[7],A=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],v=e[14],g=e[15],m=i*a-s*o,_=i*l-r*o,y=i*u-n*o,b=s*l-r*a,B=s*u-n*a,x=r*u-n*l,w=A*f-c*p,P=A*v-h*p,C=A*g-d*p,M=c*v-h*f,F=c*g-d*f,E=h*g-d*v,k=1/(m*E-_*F+y*M+b*C-B*P+x*w);return t[0]=(a*E-l*F+u*M)*k,t[1]=(-s*E+r*F-n*M)*k,t[2]=(f*x-v*B+g*b)*k,t[3]=(-c*x+h*B-d*b)*k,t[4]=(-o*E+l*C-u*P)*k,t[5]=(i*E-r*C+n*P)*k,t[6]=(-p*x+v*y-g*_)*k,t[7]=(A*x-h*y+d*_)*k,t[8]=(o*F-a*C+u*w)*k,t[9]=(-i*F+s*C-n*w)*k,t[10]=(p*B-f*y+g*m)*k,t[11]=(-A*B+c*y-d*m)*k,t[12]=(-o*M+a*P-l*w)*k,t[13]=(i*M-s*P+r*w)*k,t[14]=(-p*b+f*_-v*m)*k,t[15]=(A*b-c*_+h*m)*k,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||$.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||$.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(O=new X(3),function(e,t,i,s){return O[0]=e,O[1]=t,O[2]=i,$.translationMat4v(O,s)}),translationMat4s:function(e,t){return $.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return $.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,s){var r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;var n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;var o=s[11];s[8]+=o*e,s[9]+=o*t,s[10]+=o*i;var a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var s,r,n,o,a,l,u=$.normalizeVec4([t[0],t[1],t[2],0],[]),A=Math.sin(e),c=Math.cos(e),h=1-c,d=u[0],p=u[1],f=u[2];return s=d*p,r=p*f,n=f*d,o=d*A,a=p*A,l=f*A,(i=i||$.mat4())[0]=h*d*d+c,i[1]=h*s+l,i[2]=h*n-a,i[3]=0,i[4]=h*s-l,i[5]=h*p*p+c,i[6]=h*r+o,i[7]=0,i[8]=h*n+a,i[9]=h*r-o,i[10]=h*f*f+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,s,r){return $.rotationMat4v(e,[t,i,s],r)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new X(3);return function(t,i,s,r){return e[0]=t,e[1]=i,e[2]=s,$.scalingMat4v(e,r)}}(),scaleMat4c:function(e,t,i,s){return s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s},scaleMat4v:function(e,t){var i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:function(e){return $.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.mat4(),s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,l=r+r,u=n+n,A=s*a,c=s*l,h=s*u,d=r*l,p=r*u,f=n*u,v=o*a,g=o*l,m=o*u;return i[0]=1-(d+f),i[1]=c+m,i[2]=h-g,i[3]=0,i[4]=c-m,i[5]=1-(A+f),i[6]=p+v,i[7]=0,i[8]=h+g,i[9]=p-v,i[10]=1-(A+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=$.clamp,r=e[0],n=e[4],o=e[8],a=e[1],l=e[5],u=e[9],A=e[2],c=e[6],h=e[10];return"XYZ"===t?(i[1]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-u,h),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(o,h),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-A,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-A,h),i[2]=Math.atan2(-n,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[0]=Math.atan2(c,h),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-n,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-u,l),i[1]=Math.atan2(-A,r)):(i[0]=0,i[1]=Math.atan2(o,h))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(o,r)):(i[0]=Math.atan2(-u,h),i[1]=0)),i},composeMat4:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.mat4();return $.quaternionToRotationMat4(t,s),$.scaleMat4v(i,s),$.translateMat4v(e,s),s},decomposeMat4:function(){var e=new X(3),t=new X(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=$.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=$.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var l=$.lenVec3(e);$.determinantMat4(i)<0&&(o=-o),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);var u=1/o,A=1/a,c=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=A,t[5]*=A,t[6]*=A,t[8]*=c,t[9]*=c,t[10]*=c,$.mat4ToQuaternion(t,r),n[0]=o,n[1]=a,n[2]=l,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,s){s||(s=$.mat4());var r,n,o,a,l,u,A,c,h,d,p=e[0],f=e[1],v=e[2],g=i[0],m=i[1],_=i[2],y=t[0],b=t[1],B=t[2];return p===y&&f===b&&v===B?$.identityMat4():(r=p-y,n=f-b,o=v-B,a=m*(o*=d=1/Math.sqrt(r*r+n*n+o*o))-_*(n*=d),l=_*(r*=d)-g*o,u=g*n-m*r,(d=Math.sqrt(a*a+l*l+u*u))?(a*=d=1/d,l*=d,u*=d):(a=0,l=0,u=0),A=n*u-o*l,c=o*a-r*u,h=r*l-n*a,(d=Math.sqrt(A*A+c*c+h*h))?(A*=d=1/d,c*=d,h*=d):(A=0,c=0,h=0),s[0]=a,s[1]=A,s[2]=r,s[3]=0,s[4]=l,s[5]=c,s[6]=n,s[7]=0,s[8]=u,s[9]=h,s[10]=o,s[11]=0,s[12]=-(a*p+l*f+u*v),s[13]=-(A*p+c*f+h*v),s[14]=-(r*p+n*f+o*v),s[15]=1,s)},lookAtMat4c:function(e,t,i,s,r,n,o,a,l){return $.lookAtMat4v([e,t,i],[s,r,n],[o,a,l],[])},orthoMat4c:function(e,t,i,s,r,n,o){o||(o=$.mat4());var a=t-e,l=s-i,u=n-r;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/l,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/u,o[11]=0,o[12]=-(e+t)/a,o[13]=-(s+i)/l,o[14]=-(n+r)/u,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=$.mat4());var s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];$.addVec4(r,s,Y),$.subVec4(r,s,Z);var n=2*s[2],o=Z[0],a=Z[1],l=Z[2];return i[0]=n/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/a,i[6]=0,i[7]=0,i[8]=Y[0]/o,i[9]=Y[1]/a,i[10]=-Y[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/l,i[15]=0,i},frustumMat4:function(e,t,i,s,r,n,o){o||(o=$.mat4());var a=t-e,l=s-i,u=n-r;return o[0]=2*r/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*r/l,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(s+i)/l,o[10]=-(n+r)/u,o[11]=-1,o[12]=0,o[13]=0,o[14]=-n*r*2/u,o[15]=0,o},perspectiveMat4:function(e,t,i,s,r){var n=[],o=[];return n[2]=i,o[2]=s,o[1]=n[2]*Math.tan(e/2),n[1]=-o[1],o[0]=o[1]*t,n[0]=-o[0],$.frustumMat4v(n,o,r)},compareMat4:function(e,t){return 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:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var s,r,n,o,a,l=i||[],u=t.length,A=e[0],c=e[1],h=e[2],d=e[3],p=e[4],f=e[5],v=e[6],g=e[7],m=e[8],_=e[9],y=e[10],b=e[11],B=e[12],x=e[13],w=e[14],P=e[15],C=0;C2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2];e[3];var c=e[4],h=e[5],d=e[6];e[7];var p=e[8],f=e[9],v=e[10];e[11];var g=e[12],m=e[13],_=e[14];for(e[15],i=0;i2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],B=e[14],x=e[15];for(i=0;i3&&void 0!==arguments[3]?arguments[3]:e,r=Math.cos(i),n=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return s[0]=o*r-a*n+t[0],s[1]=o*n+a*r+t[1],e},rotateVec3X:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4:function(e,t){var i=1/e[3];return(t=t||$.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(R=new X(16),L=new X(16),U=new X(16),function(e,t,i,s){return this.transformVec3(this.mulMat4(this.inverseMat4(t,R),this.inverseMat4(i,L),U),e,s)}),lerpVec3:function(e,t,i,s,r,n){var o=n||$.vec3(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o},lerpMat4:function(e,t,i,s,r,n){var o=n||$.mat4(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o[3]=s[3]+a*(r[3]-s[3]),o[4]=s[4]+a*(r[4]-s[4]),o[5]=s[5]+a*(r[5]-s[5]),o[6]=s[6]+a*(r[6]-s[6]),o[7]=s[7]+a*(r[7]-s[7]),o[8]=s[8]+a*(r[8]-s[8]),o[9]=s[9]+a*(r[9]-s[9]),o[10]=s[10]+a*(r[10]-s[10]),o[11]=s[11]+a*(r[11]-s[11]),o[12]=s[12]+a*(r[12]-s[12]),o[13]=s[13]+a*(r[13]-s[13]),o[14]=s[14]+a*(r[14]-s[14]),o[15]=s[15]+a*(r[15]-s[15]),o},flatten:function(e){var t,i,s,r,n,o=[];for(t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:$.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=e[0]*$.DEGTORAD/2,r=e[1]*$.DEGTORAD/2,n=e[2]*$.DEGTORAD/2,o=Math.cos(s),a=Math.cos(r),l=Math.cos(n),u=Math.sin(s),A=Math.sin(r),c=Math.sin(n);return"XYZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"YXZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"ZXY"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"ZYX"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"YZX"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l-u*A*c):"XZY"===t&&(i[0]=u*a*l-o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l+u*A*c),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),s=e[0],r=e[4],n=e[8],o=e[1],a=e[5],l=e[9],u=e[2],A=e[6],c=e[10],h=s+a+c;return h>0?(t=.5/Math.sqrt(h+1),i[3]=.25/t,i[0]=(A-l)*t,i[1]=(n-u)*t,i[2]=(o-r)*t):s>a&&s>c?(t=2*Math.sqrt(1+s-a-c),i[3]=(A-l)/t,i[0]=.25*t,i[1]=(r+o)/t,i[2]=(n+u)/t):a>c?(t=2*Math.sqrt(1+a-s-c),i[3]=(n-u)/t,i[0]=(r+o)/t,i[1]=.25*t,i[2]=(l+A)/t):(t=2*Math.sqrt(1+c-s-a),i[3]=(o-r)/t,i[0]=(n+u)/t,i[1]=(l+A)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=Math.sqrt($.dotVec3(e,e)*$.dotVec3(t,t)),r=s+$.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):$.cross3Vec3(e,t,i),i[3]=r,$.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new X(16);return function(t,i,s){return s=s||$.vec3(),$.quaternionToRotationMat4(t,e),$.mat4ToEuler(e,i,s),s}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=e[0],r=e[1],n=e[2],o=e[3],a=t[0],l=t[1],u=t[2],A=t[3];return i[0]=o*a+s*A+r*u-n*l,i[1]=o*l+r*A+n*a-s*u,i[2]=o*u+n*A+s*l-r*a,i[3]=o*A-s*a-r*l-n*u,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),s=t[0],r=t[1],n=t[2],o=e[0],a=e[1],l=e[2],u=e[3],A=u*s+a*n-l*r,c=u*r+l*s-o*n,h=u*n+o*r-a*s,d=-o*s-a*r-l*n;return i[0]=A*u+d*-o+c*-l-h*-a,i[1]=c*u+d*-a+h*-o-A*-l,i[2]=h*u+d*-l+A*-a-c*-o,i},quaternionToMat4:function(e,t){t=$.identityMat4(t);var i=e[0],s=e[1],r=e[2],n=e[3],o=2*i,a=2*s,l=2*r,u=o*n,A=a*n,c=l*n,h=o*i,d=a*i,p=l*i,f=a*s,v=l*s,g=l*r;return t[0]=1-(f+g),t[1]=d+c,t[2]=p-A,t[4]=d-c,t[5]=1-(h+g),t[6]=v+u,t[8]=p+A,t[9]=v-u,t[10]=1-(h+f),t},quaternionToRotationMat4:function(e,t){var i=e[0],s=e[1],r=e[2],n=e[3],o=i+i,a=s+s,l=r+r,u=i*o,A=i*a,c=i*l,h=s*a,d=s*l,p=r*l,f=n*o,v=n*a,g=n*l;return t[0]=1-(h+p),t[4]=A-g,t[8]=c+v,t[1]=A+g,t[5]=1-(u+p),t[9]=d-f,t[2]=c-v,t[6]=d+f,t[10]=1-(u+h),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=$.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return $.normalizeQuaternion($.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=(e=$.normalizeQuaternion(e,q))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:function(e){return new X(e||6)},AABB2:function(e){return new X(e||4)},OBB3:function(e){return new X(e||32)},OBB2:function(e){return new X(e||16)},Sphere3:function(e,t,i,s){return new X([e,t,i,s])},transformOBB3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],B=e[14],x=e[15];for(i=0;ia?o:a,n[1]+=l>u?l:u,n[2]+=A>c?A:c,Math.abs($.lenVec3(n))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||$.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||$.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$.AABB3();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MAX_DOUBLE,e[3]=$.MIN_DOUBLE,e[4]=$.MIN_DOUBLE,e[5]=$.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.OBB3();return 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:function(){var e=new X(3);return function(t,i,s){i=i||$.AABB3();for(var r,n,o,a=$.MAX_DOUBLE,l=$.MAX_DOUBLE,u=$.MAX_DOUBLE,A=$.MIN_DOUBLE,c=$.MIN_DOUBLE,h=$.MIN_DOUBLE,d=0,p=t.length;dA&&(A=r),n>c&&(c=n),o>h&&(h=o);return i[0]=a,i[1]=l,i[2]=u,i[3]=A,i[4]=c,i[5]=h,i}}(),OBB3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),s>A&&(A=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r[4]=u,r[5]=A,r},points3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),s>A&&(A=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r[4]=u,r[5]=A,r},points3ToSphere3:function(){var e=new X(3);return function(t,i){i=i||$.vec4();var s,r=0,n=0,o=0,a=t.length;for(s=0;su&&(u=l);return i[3]=u,i}}(),positions3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,s){s=s||$.vec4();var r,n=0,o=0,a=0,l=i.length,u=0;for(r=0;ru&&(u=A);return s[3]=u,s}}(),OBB3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,s){s=s||$.vec4();var r,n=0,o=0,a=0,l=i.length,u=l/4;for(r=0;rc&&(c=A);return s[3]=c,s}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(),i=0,s=0,r=0,n=0,o=e.length;nt[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[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]0&&void 0!==arguments[0]?arguments[0]:$.AABB2();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MIN_DOUBLE,e[3]=$.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB2(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MIN_DOUBLE,l=$.MIN_DOUBLE,u=0,A=e.length;ua&&(a=t),i>l&&(l=i);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]3&&void 0!==arguments[3]?arguments[3]:e,r=.5*(e[0]+1),n=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(o*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:function(e,t,i,s){return 2*(1-e)*(i-t)+2*e*(s-i)},tangentQuadraticBezier3:function(e,t,i,s,r){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,i,s,r){var n=.5*(i-e),o=.5*(s-t),a=r*r;return(2*t-2*i+n+o)*(r*a)+(-3*t+3*i-2*n-o)*a+n*r+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.vec3(),r=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],u=i[2]-e[2],A=n*u-o*l,c=o*a-r*u,h=r*l-n*a,d=Math.sqrt(A*A+c*c+h*h);return 0===d?(s[0]=0,s[1]=0,s[2]=0):(s[0]=A/d,s[1]=c/d,s[2]=h/d),s},rayTriangleIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),s=new X(3),r=new X(3);return function(n,o,a,l,u,A){A=A||$.vec3();var c=$.subVec3(l,a,e),h=$.subVec3(u,a,t),d=$.cross3Vec3(o,h,i),p=$.dotVec3(c,d);if(p<1e-6)return null;var f=$.subVec3(n,a,s),v=$.dotVec3(f,d);if(v<0||v>p)return null;var g=$.cross3Vec3(f,c,r),m=$.dotVec3(o,g);if(m<0||v+m>p)return null;var _=$.dotVec3(h,g)/p;return A[0]=n[0]+_*o[0],A[1]=n[1]+_*o[1],A[2]=n[2]+_*o[2],A}}(),rayPlaneIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),s=new X(3);return function(r,n,o,a,l,u){u=u||$.vec3(),n=$.normalizeVec3(n,e);var A=$.subVec3(a,o,t),c=$.subVec3(l,o,i),h=$.cross3Vec3(A,c,s);$.normalizeVec3(h,h);var d=-$.dotVec3(o,h),p=-($.dotVec3(r,h)+d)/$.dotVec3(n,h);return u[0]=r[0]+p*n[0],u[1]=r[1]+p*n[1],u[2]=r[2]+p*n[2],u}}(),cartesianToBarycentric:function(){var e=new X(3),t=new X(3),i=new X(3);return function(s,r,n,o,a){var l=$.subVec3(o,r,e),u=$.subVec3(n,r,t),A=$.subVec3(s,r,i),c=$.dotVec3(l,l),h=$.dotVec3(l,u),d=$.dotVec3(l,A),p=$.dotVec3(u,u),f=$.dotVec3(u,A),v=c*p-h*h;if(0===v)return null;var g=1/v,m=(p*d-h*f)*g,_=(c*f-h*d)*g;return a[0]=1-m-_,a[1]=_,a[2]=m,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,s){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:$.vec3(),n=e[0],o=e[1],a=e[2];return r[0]=t[0]*n+i[0]*o+s[0]*a,r[1]=t[1]*n+i[1]*o+s[1]*a,r[2]=t[2]*n+i[2]*o+s[2]*a,r},mergeVertices:function(e,t,i,s){var r,n,o,a,l,u,A={},c=[],h=[],d=t?[]:null,p=i?[]:null,f=[],v=Math.pow(10,4),g=0;for(l=0,u=e.length;l>24&255,o=c>>16&255,n=c>>8&255,r=255&c,s=3*t[p],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,s=3*t[p+1],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,s=3*t[p+2],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,c++;return{positions:u,colors:A}},faceToVertexNormals:function(e,t){var i,s,r,n,o,a,l,u,A,c,h,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},p=d.smoothNormalsAngleThreshold||20,f={},v=[],g={},m=4,_=Math.pow(10,m);for(l=0,A=e.length;ll[3]&&(l[3]=r[h]),r[h+1]l[4]&&(l[4]=r[h+1]),r[h+2]l[5]&&(l[5]=r[h+2])}if(i.length<20||n>10)return u.triangles=i,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),u.splitDim=d;var p=(l[d]+l[d+3])/2,f=new Array(i.length),v=0,g=new Array(i.length),m=0;for(o=0,a=i.length;o2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s:function(e,t){for(var i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/l,t[s+1]=o/l,t[s+2]=a/l,s+=3}return t}};$.buildEdgeIndices=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(r,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=r.length;AI)||(F=i[P.index1],E=i[P.index2],(!S&&F>65535||E>65535)&&(S=!0),k.push(F),k.push(E));return S?new Uint32Array(k):new Uint16Array(k)}}(),$.planeClipsPositions3=function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:3,r=0,n=i.length;r=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&$.containsAABB3(e.left.aabb,s))this._insertEntity(e.left,t,i+1);else if(e.right&&$.containsAABB3(e.right.aabb,s))this._insertEntity(e.right,t,i+1);else{var r=e.aabb;ee[0]=r[3]-r[0],ee[1]=r[4]-r[1],ee[2]=r[5]-r[2];var n=0;if(ee[1]>ee[n]&&(n=1),ee[2]>ee[n]&&(n=2),!e.left){var o=r.slice();if(o[n+3]=(r[n]+r[n+3])/2,e.left={aabb:o},$.containsAABB3(o,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){var a=r.slice();if(a[n]=(r[n]+r[n+3])/2,e.right={aabb:a},$.containsAABB3(a,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}}},{key:"destroy",value:function(){var e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}]),e}(),ie=function(){function e(){w(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return C(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var 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}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),se={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 re=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r1&&void 0!==arguments[1]?arguments[1]:null;ce.push(e),ce.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,s=(new Date).getTime(),r=0;ce.length>0&&(i<0||s0&&ae>0){var t=1e3/ae;fe+=t,de.push(t),de.length>=30&&(fe-=de.shift()),se.frame.fps=Math.round(fe/de.length)}for(var i in _e.scenes)_e.scenes[i].compile();be(e),pe=e};ve=function(){ye()},ge=100,me=Date.now()+ge,function e(){var t=Date.now()-me;ve(),me+=ge,setTimeout(e,Math.max(0,ge-t))}();function be(e){var t=_e.runTasks(e+10),i=_e.getNumTasks();se.frame.tasksRun=t,se.frame.tasksScheduled=i,se.frame.tasksBudget=10}!function e(){var t=Date.now();if(ae=t-pe,pe>0&&ae>0){var i=1e3/ae;fe+=i,de.push(i),de.length>=30&&(fe-=de.shift()),se.frame.fps=Math.round(fe/de.length)}be(t),function(e){for(var t in he.time=e,_e.scenes)if(_e.scenes.hasOwnProperty(t)){var i=_e.scenes[t];he.sceneId=t,he.startTime=i.startTime,he.deltaTime=null!=he.prevTime?he.time-he.prevTime:0,i.fire("tick",he,!0)}he.prevTime=e}(t),function(){var e,t,i,s,r,n=_e.scenes,o=!1;for(r in n)n.hasOwnProperty(r)&&(e=n[r],(t=ue[r])||(t=ue[r]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),s=e.ticksPerRender,t.ticksPerRender!==s&&(t.ticksPerRender=s,t.renderCountdown=s),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=s))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(ye):requestAnimationFrame(e)}();var Be=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.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,t&&t._own(this)}return C(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Q),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+le.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var i=e.component,s=e.sceneDefault,r=e.sceneSingleton,n=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(le.isNumeric(i)||le.isString(i))){var l=i;if(!(i=this.scene.components[l]))return void this.error("Component not found: "+le.inQuotes(l))}if(!i)if(!0===r){var u=this.scene.types[n];for(var A in u)if(u.hasOwnProperty){i=u[A];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+le.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+le.inQuotes(i.id))}this._attachments||(this._attachments={});var c,h,d,p=this._attached[t];if(p){if(i&&p.id===i.id)return;var f=this._attachments[p.id];for(h=0,d=(c=f.subs).length;h=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Me=C((function e(){w(this,e),this.planes=[new Ce,new Ce,new Ce,new Ce,new Ce,new Ce]}));function Fe(e,t,i){var s=$.mulMat4(i,t,Pe),r=s[0],n=s[1],o=s[2],a=s[3],l=s[4],u=s[5],A=s[6],c=s[7],h=s[8],d=s[9],p=s[10],f=s[11],v=s[12],g=s[13],m=s[14],_=s[15];e.planes[0].set(a-r,c-l,f-h,_-v),e.planes[1].set(a+r,c+l,f+h,_+v),e.planes[2].set(a-n,c-u,f-d,_-g),e.planes[3].set(a+n,c+u,f+d,_+g),e.planes[4].set(a-o,c-A,f-p,_-m),e.planes[5].set(a+o,c+A,f+p,_+m)}function Ee(e,t){var i=Me.INSIDE,s=xe,r=we;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];for(var n=[s,r],o=0;o<6;++o){var a=e.planes[o];if(a.normal[0]*n[a.testVertex[0]][0]+a.normal[1]*n[a.testVertex[1]][1]+a.normal[2]*n[a.testVertex[2]][2]+a.offset<0)return Me.OUTSIDE;a.normal[0]*n[1-a.testVertex[0]][0]+a.normal[1]*n[1-a.testVertex[1]][1]+a.normal[2]*n[1-a.testVertex[2]][2]+a.offset<0&&(i=Me.INTERSECT)}return i}Me.INSIDE=0,Me.INTERSECT=1,Me.OUTSIDE=2;var ke=function(e){g(i,Be);var t=_(i);function i(){var e,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(w(this,i),!s.viewer)throw"[MarqueePicker] Missing config: viewer";if(!s.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";return(e=t.call(this,s.viewer.scene,s)).viewer=s.viewer,e._objectsKdTree3=s.objectsKdTree3,e._canvasMarqueeCorner1=$.vec2(),e._canvasMarqueeCorner2=$.vec2(),e._canvasMarquee=$.AABB2(),e._marqueeFrustum=new Me,e._marqueeFrustumProjMat=$.mat4(),e._pickMode=!1,e._marqueeElement=document.createElement("div"),document.body.appendChild(e._marqueeElement),e._marqueeElement.style.position="absolute",e._marqueeElement.style["z-index"]="40000005",e._marqueeElement.style.width="8px",e._marqueeElement.style.height="8px",e._marqueeElement.style.visibility="hidden",e._marqueeElement.style.top="0px",e._marqueeElement.style.left="0px",e._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",e._marqueeElement.style.opacity=1,e._marqueeElement.style["pointer-events"]="none",e}return C(i,[{key:"setMarqueeCorner1",value:function(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarqueeCorner2",value:function(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarquee",value:function(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}},{key:"setMarqueeVisible",value:function(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}},{key:"getMarqueeVisible",value:function(){return this._marqueVisible}},{key:"setPickMode",value:function(e){if(e!==i.PICK_MODE_INSIDE&&e!==i.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===i.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}},{key:"getPickMode",value:function(){return this._pickMode}},{key:"clear",value:function(){this.fire("clear",{})}},{key:"pick",value:function(){var e=this;this._updateMarquee(),this._buildMarqueeFrustum();var t=[];return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&function s(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Me.INTERSECT;if(n===Me.INTERSECT&&(n=Ee(e._marqueeFrustum,r.aabb)),n!==Me.OUTSIDE){if(r.entities)for(var o=r.entities,a=0,l=o.length;a3||i>3)&&c.pick()}})),document.addEventListener("mouseup",(function(e){s.getActive()&&0===e.button&&(clearTimeout(A),d&&(c.setMarqueeVisible(!1),d=!1,p=!1,f=!0,c.viewer.cameraControl.pointerEnabled=!0))}),!0),h.addEventListener("mousemove",(function(e){s.getActive()&&0===e.button&&p&&(clearTimeout(A),d&&(o=e.pageX,a=e.pageY,u=e.offsetX,c.setMarqueeVisible(!0),c.setMarqueeCorner2([o,a]),c.setPickMode(l0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),Se=$.vec3(),Te=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,$.transformVec4(s,t,i),$.setMat4Translation(s,i,n),n.slice()}}();function Re(e,t,i){var s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],o=e[1]-n,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=n,t[2]=a,i[0]=r,i[1]=o,i[2]=l}function Le(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,r=$.getPositionsCenter(e,Se),n=Math.round(r[0]/s)*s,o=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=n,i[1]=o,i[2]=a;var l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(var u=0,A=e.length;u0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._color=s.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=s.thickness||1,this._thicknessClickable=s.thicknessClickable||6,this._visible=!0,this._culled=!1;var r=this._wire,n=r.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===s.zIndex?"2000001":s.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._wireClickable,a=o.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===s.zIndex?"2000002":s.zIndex+1,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onMouseWheel&&o.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&o.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&o.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&o.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return C(e,[{key:"visible",get:function(){return"visible"===this._wire.style.visibility}},{key:"_update",value:function(){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,i=this._wire.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)";var s=this._wireClickable.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)"}},{key:"setStartAndEnd",value:function(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}},{key:"setColor",value:function(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}},{key:"setOpacity",value:function(e){this._wire.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}},{key:"destroy",value:function(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),tt=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!s.visible,this._culled=!1;var r=this._dot,n=r.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"40000005":s.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==s.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._dotClickable,a=o.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===s.zIndex?"40000007":s.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),o.addEventListener("click",(function(e){t.dispatchEvent(new MouseEvent("mouseover",e))})),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),t.dispatchEvent(new MouseEvent("mouseover",e))})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onMouseWheel&&o.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&o.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&o.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&o.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&o.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()})),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.borderColor)}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}},{key:"setFillColor",value:function(e){this._dot.style.background=e||"lightgreen"}},{key:"setBorderColor",value:function(e){this._dot.style.border="solid 2px"+(e||"black")}},{key:"setOpacity",value:function(e){this._dot.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}},{key:"destroy",value:function(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),it=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=s.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 r=this._label,n=r.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"5000005":s.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,s.onContextMenu,r.innerText="",t.appendChild(r),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.fillColor),this.setText(s.text),s.onMouseOver&&r.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),e.preventDefault()})),s.onMouseLeave&&r.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i),e.preventDefault()})),s.onMouseWheel&&r.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&r.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&r.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&r.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&r.addEventListener("contextmenu",(function(e){s.onContextMenu(e,i),e.preventDefault()}))}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,i,s){var r=e+.5*(i-e),n=t+.5*(s-t),o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(n)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,i,s,r,n){var o=(e+i+r)/3,a=(t+s+n)/3,l=this._label.style;l.left=Math.round(o)-20+"px",l.top=Math.round(a)-12+"px"}},{key:"setText",value:function(e){this._label.innerHTML=this._prefix+(e||"")}},{key:"setFillColor",value:function(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}},{key:"setBorderColor",value:function(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}},{key:"setOpacity",value:function(e){this._label.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}},{key:"setClickable",value:function(e){this._label.style["pointer-events"]=e?"all":"none"}},{key:"destroy",value:function(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}]),e}(),st=$.vec3(),rt=$.vec3(),nt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._color=r.color||e.defaultColor;var n=s.plugin.viewer.scene;s._originMarker=new $e(n,r.origin),s._cornerMarker=new $e(n,r.corner),s._targetMarker=new $e(n,r.target),s._originWorld=$.vec3(),s._cornerWorld=$.vec3(),s._targetWorld=$.vec3(),s._wp=new Float64Array(12),s._vp=new Float64Array(12),s._pp=new Float64Array(12),s._cp=new Int16Array(6);var o=r.onMouseOver?function(e){r.onMouseOver(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=r.onContextMenu?function(e){r.onContextMenu(e,b(s))}:null,u=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},A=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},c=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},h=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};return s._originDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._cornerDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._targetDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._originWire=new et(s._container,{color:s._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._targetWire=new et(s._container,{color:s._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._angleLabel=new it(s._container,{fillColor:s._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._visible=!1,s._originVisible=!1,s._cornerVisible=!1,s._targetVisible=!1,s._originWireVisible=!1,s._targetWireVisible=!1,s._angleVisible=!1,s._labelsVisible=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._cornerMarker.on("worldPos",(function(e){s._cornerWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){s._sectionPlanesDirty=!0,s._needUpdate()})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.cornerVisible=r.cornerVisible,s.targetVisible=r.targetVisible,s.originWireVisible=r.originWireVisible,s.targetWireVisible=r.targetWireVisible,s.angleVisible=r.angleVisible,s.labelsVisible=r.labelsVisible,s}return C(i,[{key:"_update",value:function(){if(this._visible){var 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&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){var t=-.3,i=this._originMarker.viewPos[2],s=this._cornerMarker.viewPos[2],r=this._targetMarker.viewPos[2];if(i>t||s>t||r>t)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);$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var n=this._pp,o=this._cp,a=e.canvas.canvas.getBoundingClientRect(),l=this._container.getBoundingClientRect(),u=a.top-l.top,A=a.left-l.left,c=e.canvas.boundary,h=c[2],d=c[3],p=0,f=0,v=n.length;f1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e.viewer.scene)).pointerLens=r.pointerLens,s._active=!1,s._mouseState=0,s._currentAngleMeasurement=null,s._initMarkerDiv(),s._onMouseHoverSurface=null,s._onHoverNothing=null,s._onPickedNothing=null,s._onPickedSurface=null,s._onInputMouseDown=null,s._onInputMouseUp=null,s._snapping=!1!==r.snapping,s._attachPlugin(e,r),s}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this.markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.angleMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this.markerDiv||this._initMarkerDiv(),this.angleMeasurementsPlugin;var t=this.scene;t.input;var i=t.canvas.canvas,s=this.angleMeasurementsPlugin.viewer.cameraControl,r=this.pointerLens,n=!1,o=null,a=0,l=0,u=$.vec3(),A=$.vec2();this._currentAngleMeasurement=null;var c=function e(t){return t.offsetTop+(t.offsetParent&&e(t.offsetParent))},h=function e(t){return t.offsetLeft+(t.offsetParent&&e(t.offsetParent))};this._onMouseHoverSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){t.snappedToVertex||t.snappedToEdge?(r&&(r.visible=!0,r.canvasPos=t.canvasPos,r.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,r.snapped=!0),e.markerDiv.style.background="greenyellow",e.markerDiv.style.border="2px solid green"):(r&&(r.visible=!0,r.canvasPos=t.canvasPos,r.snappedCanvasPos=t.canvasPos,r.snapped=!1),e.markerDiv.style.background="pink",e.markerDiv.style.border="2px solid red");var s=t.snappedCanvasPos||t.canvasPos;switch(n=!0,o=t.entity,u.set(t.worldPos),A.set(s),e._mouseState){case 0:e.markerDiv.style.left="".concat(h(i)+s[0]-5,"px"),e.markerDiv.style.top="".concat(c(i)+s[1]-5,"px");break;case 1:e._currentAngleMeasurement&&(e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.worldPos=t.worldPos,e._currentAngleMeasurement.corner.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer";break;case 2:e._currentAngleMeasurement&&(e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.worldPos=t.worldPos,e._currentAngleMeasurement.target.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer"}})),i.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=function(t){if(1===t.which&&!(t.clientX>a+20||t.clientXl+20||t.clientY1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"AngleMeasurements",e))._container=r.container||document.body,s._defaultControl=null,s._measurements={},s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.zIndex=r.zIndex||1e4,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new at(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,s=t.corner,r=t.target,n=new nt(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:r.entity,worldPos:r.worldPos},visible:t.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[n.id]=n,n.on("destroyed",(function(){delete e._measurements[n.id]})),n.clickable=!0,this.fire("measurementCreated",n),n}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t

";le.isArray(t)&&(t=t.join("")),t=this._renderTemplate(t.trim());var i=document.createRange().createContextualFragment(t);this._marker=i.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(function(){e.plugin.fire("markerClicked",e)})),this._marker.addEventListener("mouseenter",(function(){e.plugin.fire("markerMouseEnter",e)})),this._marker.addEventListener("mouseleave",(function(){e.plugin.fire("markerMouseLeave",e)})),this._marker.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);var s=this._labelHTML||"

";le.isArray(s)&&(s=s.join("")),s=this._renderTemplate(s.trim());var r=document.createRange().createContextualFragment(s);this._label=r.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}},{key:"setMarkerShown",value:function(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}},{key:"getMarkerShown",value:function(){return this._markerShown}},{key:"setLabelShown",value:function(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}},{key:"getLabelShown",value:function(){return this._labelShown}},{key:"setField",value:function(e,t){this._values[e]=t||"",this._htmlDirty=!0}},{key:"getField",value:function(e){return this._values[e]}},{key:"setValues",value:function(e){for(var t in e)if(e.hasOwnProperty(t)){var i=e[t];this.setField(t,i)}}},{key:"getValues",value:function(){return this._values}},{key:"destroy",value:function(){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),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),At=$.vec3(),ct=$.vec3(),ht=$.vec3(),dt=function(e){g(i,De);var t=_(i);function i(e,s){var r;return w(this,i),(r=t.call(this,"Annotations",e))._labelHTML=s.labelHTML||"
",r._markerHTML=s.markerHTML||"
",r._container=s.container||document.body,r._values=s.values||{},r.annotations={},r.surfaceOffset=s.surfaceOffset,r}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){if("clearAnnotations"===e)this.clear()}},{key:"surfaceOffset",get:function(){return this._surfaceOffset},set:function(e){null==e&&(e=.3),this._surfaceOffset=e}},{key:"createAnnotation",value:function(e){var t,i,s=this;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){var r=e.pickResult;if(r.worldPos&&r.worldNormal){var n=$.normalizeVec3(r.worldNormal,At),o=$.mulVec3Scalar(n,this._surfaceOffset,ct);t=$.addVec3(r.worldPos,o,ht),i=r.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var a=null;e.markerElementId&&((a=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var l=null;e.labelElementId&&((l=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var u=new ut(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:a,labelElement:l,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:le.apply(e.values,le.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[u.id]=u,u.on("destroyed",(function(){delete s.annotations[u.id],s.fire("annotationDestroyed",u.id)})),this.fire("annotationCreated",u.id),u}},{key:"destroyAnnotation",value:function(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}},{key:"clear",value:function(){for(var e=Object.keys(this.annotations),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._canvas=r.canvas,s._element=null,s._isCustom=!1,r.elementId&&(s._element=document.getElementById(r.elementId),s._element?s._adjustPosition():s.error("Can't find given Spinner HTML element: '"+r.elementId+"' - will automatically create default element")),s._element||s._createDefaultSpinner(),s.processes=0,s}return C(i,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var 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)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),i}(),ft=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],vt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._backgroundColor=$.vec3([r.backgroundColor?r.backgroundColor[0]:1,r.backgroundColor?r.backgroundColor[1]:1,r.backgroundColor?r.backgroundColor[2]:1]),s._backgroundColorFromAmbientLight=!!r.backgroundColorFromAmbientLight,s.canvas=r.canvas,s.gl=null,s.webgl2=!1,s.transparent=!!r.transparent,s.contextAttr=r.contextAttr||{},s.contextAttr.alpha=s.transparent,s.contextAttr.preserveDrawingBuffer=!!s.contextAttr.preserveDrawingBuffer,s.contextAttr.stencil=!1,s.contextAttr.premultipliedAlpha=!!s.contextAttr.premultipliedAlpha,s.contextAttr.antialias=!1!==s.contextAttr.antialias,s.resolutionScale=r.resolutionScale,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary=[s.canvas.offsetLeft,s.canvas.offsetTop,s.canvas.clientWidth,s.canvas.clientHeight],s._initWebGL(r);var n=b(s);s.canvas.addEventListener("webglcontextlost",s._webglcontextlostListener=function(e){console.time("webglcontextrestored"),n.scene._webglContextLost(),n.fire("webglcontextlost"),e.preventDefault()},!1),s.canvas.addEventListener("webglcontextrestored",s._webglcontextrestoredListener=function(e){n._initWebGL(),n.gl&&(n.scene._webglContextRestored(n.gl),n.fire("webglcontextrestored",n.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=!0,a=new ResizeObserver((function(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){t.value.contentBoxSize&&(o=!0)}}catch(e){i.e(e)}finally{i.f()}}));return a.observe(s.canvas),s._tick=s.scene.on("tick",(function(){o&&(o=!1,n.canvas.width=Math.round(n.canvas.clientWidth*n._resolutionScale),n.canvas.height=Math.round(n.canvas.clientHeight*n._resolutionScale),n.boundary[0]=n.canvas.offsetLeft,n.boundary[1]=n.canvas.offsetTop,n.boundary[2]=n.canvas.clientWidth,n.boundary[3]=n.canvas.clientHeight,n.fire("boundary",n.boundary))})),s._spinner=new pt(s.scene,{canvas:s.canvas,elementId:r.spinnerElementId}),s}return C(i,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(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()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+$.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e0?mt.FS_MAX_FLOAT_PRECISION="highp":yt.getShaderPrecisionFormat(yt.FRAGMENT_SHADER,yt.MEDIUM_FLOAT).precision>0?mt.FS_MAX_FLOAT_PRECISION="mediump":mt.FS_MAX_FLOAT_PRECISION="lowp":mt.FS_MAX_FLOAT_PRECISION="mediump",mt.DEPTH_BUFFER_BITS=yt.getParameter(yt.DEPTH_BITS),mt.MAX_TEXTURE_SIZE=yt.getParameter(yt.MAX_TEXTURE_SIZE),mt.MAX_CUBE_MAP_SIZE=yt.getParameter(yt.MAX_CUBE_MAP_TEXTURE_SIZE),mt.MAX_RENDERBUFFER_SIZE=yt.getParameter(yt.MAX_RENDERBUFFER_SIZE),mt.MAX_TEXTURE_UNITS=yt.getParameter(yt.MAX_COMBINED_TEXTURE_IMAGE_UNITS),mt.MAX_TEXTURE_IMAGE_UNITS=yt.getParameter(yt.MAX_TEXTURE_IMAGE_UNITS),mt.MAX_VERTEX_ATTRIBS=yt.getParameter(yt.MAX_VERTEX_ATTRIBS),mt.MAX_VERTEX_UNIFORM_VECTORS=yt.getParameter(yt.MAX_VERTEX_UNIFORM_VECTORS),mt.MAX_FRAGMENT_UNIFORM_VECTORS=yt.getParameter(yt.MAX_FRAGMENT_UNIFORM_VECTORS),mt.MAX_VARYING_VECTORS=yt.getParameter(yt.MAX_VARYING_VECTORS),yt.getSupportedExtensions().forEach((function(e){mt.SUPPORTED_EXTENSIONS[e]=!0})))}var bt=function(){function e(){w(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return C(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"snappedCanvasPos",get:function(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null},set:function(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}]),e}(),Bt=function(){function e(t,i,s){if(w(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,s),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var r=s.split("\n"),n=[],o=0;o0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),s.push(t);return s.join("\n")}function Mt(e){console.error(e.join("\n"))}var Ft=function(){function e(t,i){w(this,e),this.id=Pt.addItem({}),this.source=i,this.init(t)}return C(e,[{key:"init",value:function(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 Bt(e,e.VERTEX_SHADER,Ct(this.source.vertex)),this._fragmentShader=new Bt(e,e.FRAGMENT_SHADER,Ct(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Mt(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Mt(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Mt(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Mt(this.errors);var t,i,s,r,n;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){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 Mt(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.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)}},{key:"setData",value:function(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)))}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),kt=function(){function e(t,i){w(this,e),this.scene=t,this.aabb=$.AABB3(),this.origin=$.vec3(i),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}return C(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var 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}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){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()}},{key:"_buildMarkerList",value:function(){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}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t-t)a._setVisible(!1);else{var l=a.canvasPos,u=l[0],A=l[1];u+10<0||A+10<0||u-10>s||A-10>r?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[n++]=u,this.pixels[n++]=A):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):i.push("clipPos.z += -0.001;"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Ft(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r0)for(var h=s.sectionPlanes,d=0;d= ( 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);var s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Et(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Et(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Et(i,i.ELEMENT_ARRAY_BUFFER,n,n.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),Lt=new Float32Array(Vt(17,[0,1])),Ut=new Float32Array(Vt(17,[1,0])),Ot=new Float32Array(function(e,t){for(var i=[],s=0;s<=e;s++)i.push(Ht(s,t));return i}(17,4)),Nt=new Float32Array(2),Qt=function(){function e(t){w(this,e),this._scene=t,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()}return C(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new Ft(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 ".concat(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);var t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Et(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Et(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Et(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,i){var s=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;s._scene.camera.on("projMatrix",(function(){e=!0}));var t=$.mat4();return function(){return e&&$.inverseMat4(o.camera.projMatrix,t),t}}());var r=this._scene.canvas.gl,n=this._program,o=this._scene,a=r.drawingBufferWidth,l=r.drawingBufferHeight,u=o.camera.project._state,A=u.near,c=u.far;r.viewport(0,0,a,l),r.clearColor(0,0,0,1),r.enable(r.DEPTH_TEST),r.disable(r.BLEND),r.frontFace(r.CCW),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),n.bind(),Nt[0]=a,Nt[1]=l,r.uniform2fv(this._uViewport,Nt),r.uniform1f(this._uCameraNear,A),r.uniform1f(this._uCameraFar,c),r.uniform1f(this._uDepthCutoff,.01),0===i?r.uniform2fv(this._uSampleOffsets,Ut):r.uniform2fv(this._uSampleOffsets,Lt),r.uniform1fv(this._uSampleWeights,Ot);var h=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,h,0),n.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),r.drawElements(r.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Ht(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Vt(e,t){for(var i=[],s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}var jt=function(){function e(t,i,s){w(this,e),s=s||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}return C(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){if(this._touch.apply(this,arguments),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"createTexture",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}},{key:"_touch",value:function(){var e,t,i=this,s=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=s.drawingBufferWidth,t=s.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;this.buffer.textures.forEach((function(e){return s.deleteTexture(e)})),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}for(var r,n=[],o=arguments.length,a=new Array(o),l=0;l0?n.push.apply(n,A(a.map((function(s){return i.createTexture(e,t,s)})))):n.push(this.createTexture(e,t)),this._hasDepthTexture&&(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,e,t,0,s.DEPTH_COMPONENT,s.FLOAT,null));var u=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,u),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,e,t);var c=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,c);for(var h=0;h0&&s.drawBuffers(n.map((function(e,t){return s.COLOR_ATTACHMENT0+t}))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,r,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,u),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,c),!s.isFramebuffer(c))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);var d=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(d){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+d}this.buffer={framebuf:c,renderbuf:u,texture:n[0],textures:n,depthTexture:r,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,u=new r(n),A=this.gl;return A.readBuffer(A.COLOR_ATTACHMENT0+o),A.readPixels(a,l,1,1,i||A.RGBA,s||A.UNSIGNED_BYTE,u,0),u}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,n=new i(this.buffer.width*this.buffer.height*s),o=this.gl;return o.readBuffer(o.COLOR_ATTACHMENT0+r),o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,n,0),n}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,n=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=this.buffer.width,a=this.buffer.height,l=a/2|0,u=4*o,A=new Uint8Array(4*o),c=0;c0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,i=this.buffer.width,s=this.buffer.height,r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){var n=document.createElement("canvas"),o=n.getContext("2d");n.width=i,n.height=s,r={pixelData:new e(i*s*t),canvas:n,context:o,imageData:o.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var 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))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;this.buffer.textures.forEach((function(t){return e.deleteTexture(t)})),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),Gt=function(){function e(t){w(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return C(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,s=i[e];return s||(s=new jt(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}();function zt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}var Kt=function(e,t){t=t||{};var i=new gt(e),s=e.canvas.canvas,r=e.canvas.gl,n=!!t.transparent,o=t.alphaDepthMask,a=new Q({}),l={},u={},A=!0,c=!0,h=!0,d=!0,p=!0,f=!0,v=!0,g=!0,m=new Gt(e),_=!1,y=new Rt(e),b=new Qt(e);function B(){A&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],i=t.drawableMap,s=t.drawableListPreCull,r=0;for(var n in i)i.hasOwnProperty(n)&&(s[r++]=i[n]);s.length=r}}(),A=!1,c=!0),c&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),c=!1,h=!0),h&&function(){for(var e in l)if(l.hasOwnProperty(e)){for(var t=l[e],i=t.drawableListPreCull,s=t.drawableList,r=0,n=0,o=i.length;n0)for(i.withSAO=!0,I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||G>0||N>0||Q>0){if(r.enable(r.CULL_FACE),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):(r.blendEquation(r.FUNC_ADD),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,o||r.depthMask(!1),(N>0||Q>0)&&r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),Q>0)for(I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||K>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),K>0)for(I=0;I0)for(I=0;I0||X>0||z>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),r.enable(r.CULL_FACE),X>0)for(I=0;I0)for(I=0;I0||Y>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),Y>0)for(I=0;I0)for(I=0;I0||q>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),q>0)for(I=0;I0)for(I=0;I1&&void 0!==arguments[1]?arguments[1]:o;p.reset(),B();var f=null,v=null;for(var g in p.pickSurface=h.pickSurface,h.canvasPos?(u[0]=h.canvasPos[0],u[1]=h.canvasPos[1],f=e.camera.viewMatrix,v=e.camera.projMatrix,p.canvasPos=h.canvasPos):(h.matrix?(f=h.matrix,v=e.camera.projMatrix):(A.set(h.origin||[0,0,0]),c.set(h.direction||[0,0,1]),d=$.addVec3(A,c,t),r[0]=Math.random(),r[1]=Math.random(),r[2]=Math.random(),$.normalizeVec3(r),$.cross3Vec3(c,r,n),f=$.lookAtMat4v(A,d,n,i),v=e.camera.ortho.matrix,p.origin=A,p.direction=c),u[0]=.5*s.clientWidth,u[1]=.5*s.clientHeight),l)if(l.hasOwnProperty(g))for(var _=l[g].drawableList,y=0,b=_.length;y4&&void 0!==arguments[4]?arguments[4]:C;if(!n&&!o)return this.pick({canvasPos:t,pickSurface:!0});var A=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickZNear=e.camera.project.near,i.pickZFar=e.camera.project.far,s=s||30;var c=m.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*s+1,2*s+1]});i.snapVectorA=[k(t[0]*A,r.drawingBufferWidth),I(t[1]*A,r.drawingBufferHeight)],i.snapInvVectorAB=[r.drawingBufferWidth/(2*s),r.drawingBufferHeight/(2*s)],c.bind(r.RGBA32I,r.RGBA32I,r.RGBA8UI),r.viewport(0,0,c.size[0],c.size[1]),r.enable(r.DEPTH_TEST),r.frontFace(r.CCW),r.disable(r.CULL_FACE),r.depthMask(!0),r.disable(r.BLEND),r.depthFunc(r.LEQUAL),r.clear(r.DEPTH_BUFFER_BIT),r.clearBufferiv(r.COLOR,0,new Int32Array([0,0,0,0])),r.clearBufferiv(r.COLOR,1,new Int32Array([0,0,0,0])),r.clearBufferuiv(r.COLOR,2,new Uint32Array([0,0,0,0]));var h=e.camera.viewMatrix,d=e.camera.projMatrix;for(var p in l)if(l.hasOwnProperty(p))for(var f=l[p].drawableList,v=0,g=f.length;v0){var j=Math.floor(V/4),G=c.size[0],z=j%G-Math.floor(G/2),K=Math.floor(j/G)-Math.floor(G/2),W=Math.sqrt(Math.pow(z,2)+Math.pow(K,2));H.push({x:z,y:K,dist:W,isVertex:n&&o?B[V+3]>b.length/2:n,result:[B[V+0],B[V+1],B[V+2],B[V+3]],normal:[x[V+0],x[V+1],x[V+2],x[V+3]],id:[w[V+0],w[V+1],w[V+2],w[V+3]]})}var X=null,J=null,Y=null,Z=null;if(H.length>0){H.sort((function(e,t){return e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist})),Z=H[0].isVertex?"vertex":"edge";var q=H[0].result,ee=H[0].normal,te=H[0].id,ie=b[q[3]],se=ie.origin,re=ie.coordinateScale;J=$.normalizeVec3([ee[0]/$.MAX_INT,ee[1]/$.MAX_INT,ee[2]/$.MAX_INT]),X=[q[0]*re[0]+se[0],q[1]*re[1]+se[1],q[2]*re[2]+se[2]],Y=a.items[te[0]+(te[1]<<8)+(te[2]<<16)+(te[3]<<24)]}if(null===P&&null==X)return null;var ne=null;null!==X&&(ne=e.camera.projectWorldPos(X));var oe=Y&&Y.delegatePickedEntity?Y.delegatePickedEntity():Y;return u.reset(),u.snappedToEdge="edge"===Z,u.snappedToVertex="vertex"===Z,u.worldPos=X,u.worldNormal=J,u.entity=oe,u.canvasPos=t,u.snappedCanvasPos=ne||t,u}),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new St(e,m),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){for(var e in B(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e))for(var t=l[e].drawableList,s=0,n=t.length;s0&&void 0!==arguments[0]?arguments[0]:{},t=m.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),_=!0},this.renderSnapshot=function(){_&&(m.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),h=!0)},this.readSnapshot=function(e){return m.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return m.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){_&&(m.getRenderBuffer("snapshot").unbind(),_=!1)},this.destroy=function(){l={},u={},m.destroy(),y.destroy(),b.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Wt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).KEY_BACKSPACE=8,s.KEY_TAB=9,s.KEY_ENTER=13,s.KEY_SHIFT=16,s.KEY_CTRL=17,s.KEY_ALT=18,s.KEY_PAUSE_BREAK=19,s.KEY_CAPS_LOCK=20,s.KEY_ESCAPE=27,s.KEY_PAGE_UP=33,s.KEY_PAGE_DOWN=34,s.KEY_END=35,s.KEY_HOME=36,s.KEY_LEFT_ARROW=37,s.KEY_UP_ARROW=38,s.KEY_RIGHT_ARROW=39,s.KEY_DOWN_ARROW=40,s.KEY_INSERT=45,s.KEY_DELETE=46,s.KEY_NUM_0=48,s.KEY_NUM_1=49,s.KEY_NUM_2=50,s.KEY_NUM_3=51,s.KEY_NUM_4=52,s.KEY_NUM_5=53,s.KEY_NUM_6=54,s.KEY_NUM_7=55,s.KEY_NUM_8=56,s.KEY_NUM_9=57,s.KEY_A=65,s.KEY_B=66,s.KEY_C=67,s.KEY_D=68,s.KEY_E=69,s.KEY_F=70,s.KEY_G=71,s.KEY_H=72,s.KEY_I=73,s.KEY_J=74,s.KEY_K=75,s.KEY_L=76,s.KEY_M=77,s.KEY_N=78,s.KEY_O=79,s.KEY_P=80,s.KEY_Q=81,s.KEY_R=82,s.KEY_S=83,s.KEY_T=84,s.KEY_U=85,s.KEY_V=86,s.KEY_W=87,s.KEY_X=88,s.KEY_Y=89,s.KEY_Z=90,s.KEY_LEFT_WINDOW=91,s.KEY_RIGHT_WINDOW=92,s.KEY_SELECT_KEY=93,s.KEY_NUMPAD_0=96,s.KEY_NUMPAD_1=97,s.KEY_NUMPAD_2=98,s.KEY_NUMPAD_3=99,s.KEY_NUMPAD_4=100,s.KEY_NUMPAD_5=101,s.KEY_NUMPAD_6=102,s.KEY_NUMPAD_7=103,s.KEY_NUMPAD_8=104,s.KEY_NUMPAD_9=105,s.KEY_MULTIPLY=106,s.KEY_ADD=107,s.KEY_SUBTRACT=109,s.KEY_DECIMAL_POINT=110,s.KEY_DIVIDE=111,s.KEY_F1=112,s.KEY_F2=113,s.KEY_F3=114,s.KEY_F4=115,s.KEY_F5=116,s.KEY_F6=117,s.KEY_F7=118,s.KEY_F8=119,s.KEY_F9=120,s.KEY_F10=121,s.KEY_F11=122,s.KEY_F12=123,s.KEY_NUM_LOCK=144,s.KEY_SCROLL_LOCK=145,s.KEY_SEMI_COLON=186,s.KEY_EQUAL_SIGN=187,s.KEY_COMMA=188,s.KEY_DASH=189,s.KEY_PERIOD=190,s.KEY_FORWARD_SLASH=191,s.KEY_GRAVE_ACCENT=192,s.KEY_OPEN_BRACKET=219,s.KEY_BACK_SLASH=220,s.KEY_CLOSE_BRACKET=221,s.KEY_SINGLE_QUOTE=222,s.KEY_SPACE=32,s.element=r.element,s.altDown=!1,s.ctrlDown=!1,s.mouseDownLeft=!1,s.mouseDownMiddle=!1,s.mouseDownRight=!1,s.keyDown=[],s.enabled=!0,s.keyboardEnabled=!0,s.mouseover=!1,s.mouseCanvasPos=$.vec2(),s._keyboardEventsElement=r.keyboardEventsElement||document,s._bindEvents(),s}return C(i,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}});var t=this.scene.tickify((function(){return e.fire("mousemove",e.mouseCanvasPos,!0)}));this.element.addEventListener("mousemove",this._mouseMoveListener=function(i){e.enabled&&(e._getMouseCanvasPos(i),t(),e.mouseover&&i.preventDefault())});var i=this.scene.tickify((function(t){e.fire("mousewheel",t,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=function(t,s){if(e.enabled){var r=Math.max(-1,Math.min(1,40*-t.deltaY));i(r)}},{passive:!0});var s,r;this.on("mousedown",(function(e){s=e[0],r=e[1]})),this.on("mouseup",(function(t){s>=t[0]-2&&s<=t[0]+2&&r>=t[1]-2&&r<=t[1]+2&&e.fire("mouseclicked",t,!0)})),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getMouseCanvasPos",value:function(e){if(e){for(var t=e.target,i=0,s=0;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._unbindEvents()}}]),i}(),Xt=new Q({}),Jt=function(){function e(t){for(var i in w(this,e),this.id=Xt.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return C(e,[{key:"destroy",value:function(){Xt.removeItem(this.id)}}]),e}(),Yt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({boundary:[0,0,100,100]}),s.boundary=r.boundary,s.autoBoundary=r.autoBoundary,s}return C(i,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Zt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s._fov=60,s._canvasResized=s.scene.canvas.on("boundary",s._needUpdate,b(s)),s.fov=r.fov,s.fovAxis=r.fovAxis,s.near=r.near,s.far=r.far,s}return C(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis,s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),$.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(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))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),qt=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.scale=r.scale,s.near=r.near,s.far=r.far,s._onCanvasBoundary=s.scene.canvas.on("boundary",s._needUpdate,b(s)),s}return C(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,s,r=this.scene,n=.5*this._scale,o=r.canvas.boundary,a=o[2],l=o[3],u=a/l;a>l?(e=-n,t=n,i=n/u,s=-n/u):(e=-n*u,t=n*u,i=n,s=-n),$.orthoMat4c(e,t,s,i,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),$t=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._left=-1,s._right=1,s._bottom=-1,s._top=1,s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.left=r.left,s.right=r.right,s.bottom=r.bottom,s.top=r.top,s.near=r.near,s.far=r.far,s}return C(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){$.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)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),ei=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).camera=e,s._state=new Jt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4()}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!1,s.matrix=r.matrix,s}return C(i,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(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)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),ti=$.vec3(),ii=$.vec3(),si=$.vec3(),ri=$.vec3(),ni=$.vec3(),oi=$.vec3(),ai=$.vec4(),li=$.vec4(),ui=$.vec4(),Ai=$.mat4(),ci=$.mat4(),hi=$.vec3(),di=$.vec3(),pi=$.vec3(),fi=$.vec3(),vi=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({deviceMatrix:$.mat4(),hasDeviceMatrix:!1,matrix:$.mat4(),normalMatrix:$.mat4(),inverseMatrix:$.mat4()}),s._perspective=new Zt(b(s)),s._ortho=new qt(b(s)),s._frustum=new $t(b(s)),s._customProjection=new ei(b(s)),s._project=s._perspective,s._eye=$.vec3([0,0,10]),s._look=$.vec3([0,0,0]),s._up=$.vec3([0,1,0]),s._worldUp=$.vec3([0,1,0]),s._worldRight=$.vec3([1,0,0]),s._worldForward=$.vec3([0,0,-1]),s.deviceMatrix=r.deviceMatrix,s.eye=r.eye,s.look=r.look,s.up=r.up,s.worldAxis=r.worldAxis,s.gimbalLock=r.gimbalLock,s.constrainPitch=r.constrainPitch,s.projection=r.projection,s._perspective.on("matrix",(function(){"perspective"===s._projectionType&&s.fire("projMatrix",s._perspective.matrix)})),s._ortho.on("matrix",(function(){"ortho"===s._projectionType&&s.fire("projMatrix",s._ortho.matrix)})),s._frustum.on("matrix",(function(){"frustum"===s._projectionType&&s.fire("projMatrix",s._frustum.matrix)})),s._customProjection.on("matrix",(function(){"customProjection"===s._projectionType&&s.fire("projMatrix",s._customProjection.matrix)})),s}return C(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?($.subVec3(this._eye,this._look,hi),$.normalizeVec3(hi,di),$.mulVec3Scalar(di,1e3,pi),$.addVec3(this._look,pi,fi),e=fi):e=this._eye,t.hasDeviceMatrix?($.lookAtMat4v(e,this._look,this._up,ci),$.mulMat4(t.deviceMatrix,ci,t.matrix)):$.lookAtMat4v(e,this._look,this._up,t.matrix),$.inverseMat4(this._state.matrix,this._state.inverseMatrix),$.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=$.subVec3(this._eye,this._look,ti);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Ai),t=$.transformPoint3(Ai,t,ii),this.eye=$.addVec3(this._look,t,si),this.up=$.transformPoint3(Ai,this._up,ri)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._eye,this._look,ti),i=$.cross3Vec3($.normalizeVec3(t,ii),$.normalizeVec3(this._up,si));$.rotationMat4v(.0174532925*e,i,Ai),t=$.transformPoint3(Ai,t,ri),this.up=$.transformPoint3(Ai,this._up,ni),this.eye=$.addVec3(t,this._look,oi)}}},{key:"yaw",value:function(e){var t=$.subVec3(this._look,this._eye,ti);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,Ai),t=$.transformPoint3(Ai,t,ii),this.look=$.addVec3(t,this._eye,si),this._gimbalLock&&(this.up=$.transformPoint3(Ai,this._up,ri))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._look,this._eye,ti),i=$.cross3Vec3($.normalizeVec3(t,ii),$.normalizeVec3(this._up,si));$.rotationMat4v(.0174532925*e,i,Ai),this.up=$.transformPoint3(Ai,this._up,oi),t=$.transformPoint3(Ai,t,ri),this.look=$.addVec3(t,this._eye,ni)}}},{key:"pan",value:function(e){var t,i=$.subVec3(this._eye,this._look,ti),s=[0,0,0];if(0!==e[0]){var r=$.cross3Vec3($.normalizeVec3(i,[]),$.normalizeVec3(this._up,ii));t=$.mulVec3Scalar(r,e[0]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]}0!==e[1]&&(t=$.mulVec3Scalar($.normalizeVec3(this._up,si),e[1]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),0!==e[2]&&(t=$.mulVec3Scalar($.normalizeVec3(i,ri),e[2]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),this.eye=$.addVec3(this._eye,s,ni),this.look=$.addVec3(this._look,s,oi)}},{key:"zoom",value:function(e){var t=$.subVec3(this._eye,this._look,ti),i=Math.abs($.lenVec3(t,ii)),s=Math.abs(i+e);if(!(s<.5)){var r=$.normalizeVec3(t,si);this.eye=$.addVec3(this._look,$.mulVec3Scalar(r,s),ri)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(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)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=$.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)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return $.lenVec3($.subVec3(this._look,this._eye,ti))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(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))}},{key:"project",get:function(){return this._project}},{key:"projectWorldPos",value:function(e){var t=ai,i=li,s=ui;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,$.mulMat4v4(this.viewMatrix,t,i),$.mulMat4v4(this.projMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;var r=this.scene.canvas.canvas,n=r.offsetWidth/2,o=r.offsetHeight/2;return[s[0]*n+n,s[1]*o+o]}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),gi=function(e){g(i,Be);var t=_(i);function i(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),t.call(this,e,s)}return C(i,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),i}(),mi=function(e){g(i,gi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._shadowRenderBuf=null,s._shadowViewMatrix=null,s._shadowProjMatrix=null,s._shadowViewMatrixDirty=!0,s._shadowProjMatrixDirty=!0;var n=s.scene.camera,o=s.scene.canvas;return s._onCameraViewMatrix=n.on("viewMatrix",(function(){s._shadowViewMatrixDirty=!0})),s._onCameraProjMatrix=n.on("projMatrix",(function(){s._shadowProjMatrixDirty=!0})),s._onCanvasBoundary=o.on("boundary",(function(){s._shadowProjMatrixDirty=!0})),s._state=new Jt({type:"dir",dir:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,space:r.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=$.identityMat4());var e=s.scene.camera,t=s._state.dir,i=e.look,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];$.lookAtMat4v(r,i,[0,1,0],s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:function(){return s._shadowProjMatrixDirty&&(s._shadowProjMatrix||(s._shadowProjMatrix=$.identityMat4()),$.orthoMat4c(-40,40,-40,40,-40,80,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1),s._shadowProjMatrix},getShadowRenderBuf:function(){return s._shadowRenderBuf||(s._shadowRenderBuf=new jt(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf}}),s.dir=r.dir,s.color=r.color,s.intensity=r.intensity,s.castsShadow=r.castsShadow,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}(),_i=function(e){g(i,gi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state={type:"ambient",color:$.vec3([.7,.7,.7]),intensity:1},s.color=r.color,s.intensity=r.intensity,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),i}(),yi=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),s=t.call(this,e,r),se.memory.meshes++,s}return C(i,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),se.memory.meshes--}}]),i}(),bi=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(r,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=r.length;AI)||(F=i[P.index1],E=i[P.index2],(!S&&F>65535||E>65535)&&(S=!0),k.push(F),k.push(E));return S?new Uint32Array(k):new Uint16Array(k)}}();var Bi=function(){var e=$.mat4(),t=$.mat4();return function(i,s){s=s||$.mat4();var r=i[0],n=i[1],o=i[2],a=i[3]-r,l=i[4]-n,u=i[5]-o,A=65535;return $.identityMat4(e),$.translationMat4v(i,e),$.identityMat4(t),$.scalingMat4v([a/A,l/A,u/A],t),$.mulMat4(e,t,s),s}}(),xi=function(){var e=$.mat4(),t=$.mat4();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);for(n=0;n=0?1:-1),a=(1-Math.abs(r))*(n>=0?1:-1);r=o,n=a}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function Ci(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Mi(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var Fi={getPositionsBounds:function(e){var t,i,s=new Float32Array(3),r=new Float32Array(3);for(t=0;t<3;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,s=new Float32Array(2),r=new Float32Array(2);for(t=0;t<2;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;sr&&(i=t,r=s),(s=Mi(e,o,Ci(t=Pi(e,o,"floor","ceil"))))>r&&(i=t,r=s),(s=Mi(e,o,Ci(t=Pi(e,o,"ceil","ceil"))))>r&&(i=t,r=s),n[o]=i[0],n[o+1]=i[1];return n},decompressNormals:function(e,t){for(var i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/l,t[s+1]=o/l,t[s+2]=a/l,s+=3}return t},decompressNormal:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},Ei=se.memory,ki=$.AABB3(),Ii=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._state=new Jt({compressGeometry:!!r.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),s._numTriangles=0,s._edgeThreshold=r.edgeThreshold||10,s._edgeIndicesBuf=null,s._pickTrianglePositionsBuf=null,s._pickTriangleColorsBuf=null,s._aabbDirty=!0,s._boundingSphere=!0,s._aabb=null,s._aabbDirty=!0,s._obb=null,s._obbDirty=!0;var n=s._state,o=s.scene.canvas.gl;switch(r.primitive=r.primitive||"triangles",r.primitive){case"points":n.primitive=o.POINTS,n.primitiveName=r.primitive;break;case"lines":n.primitive=o.LINES,n.primitiveName=r.primitive;break;case"line-loop":n.primitive=o.LINE_LOOP,n.primitiveName=r.primitive;break;case"line-strip":n.primitive=o.LINE_STRIP,n.primitiveName=r.primitive;break;case"triangles":n.primitive=o.TRIANGLES,n.primitiveName=r.primitive;break;case"triangle-strip":n.primitive=o.TRIANGLE_STRIP,n.primitiveName=r.primitive;break;case"triangle-fan":n.primitive=o.TRIANGLE_FAN,n.primitiveName=r.primitive;break;default:s.error("Unsupported value for 'primitive': '"+r.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),n.primitive=o.TRIANGLES,n.primitiveName=r.primitive}if(r.positions)if(s._state.compressGeometry){var a=Fi.getPositionsBounds(r.positions),l=Fi.compressPositions(r.positions,a.min,a.max);n.positions=l.quantized,n.positionsDecodeMatrix=l.decodeMatrix}else n.positions=r.positions.constructor===Float32Array?r.positions:new Float32Array(r.positions);if(r.colors&&(n.colors=r.colors.constructor===Float32Array?r.colors:new Float32Array(r.colors)),r.uv)if(s._state.compressGeometry){var u=Fi.getUVBounds(r.uv),A=Fi.compressUVs(r.uv,u.min,u.max);n.uv=A.quantized,n.uvDecodeMatrix=A.decodeMatrix}else n.uv=r.uv.constructor===Float32Array?r.uv:new Float32Array(r.uv);return r.normals&&(s._state.compressGeometry?n.normals=Fi.compressNormals(r.normals):n.normals=r.normals.constructor===Float32Array?r.normals:new Float32Array(r.normals)),r.indices&&(n.indices=r.indices.constructor===Uint32Array||r.indices.constructor===Uint16Array?r.indices:new Uint32Array(r.indices),"triangles"===s._state.primitiveName&&(s._numTriangles=r.indices.length/3)),s._buildHash(),Ei.meshes++,s._buildVBOs(),s}return C(i,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Ei.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Et(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Ei.positions+=e.positionsBuf.numItems),e.normals){var i=e.compressGeometry;e.normalsBuf=new Et(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Ei.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Et(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Ei.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Et(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Ei.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=bi(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Ei.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=$.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Et(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Et(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Ei.positions+=this._pickTrianglePositionsBuf.numItems,Ei.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Fi.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){var s=Fi.getPositionsBounds(e),r=Fi.compressPositions(e,s.min,s.max);e=r.quantized,t.positionsDecodeMatrix=r.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Fi.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Fi.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=$.AABB3()),$.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=$.OBB3()),$.positions3ToAABB3(this._state.positions,ki,this._state.positionsDecodeMatrix),$.AABB3ToOBB3(ki,this._obb),this._obbDirty=!1),this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Ei.meshes--}}]),i}();function Di(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);var r=e.center,n=r?r[0]:0,o=r?r[1]:0,a=r?r[2]:0,l=-t+n,u=-i+o,A=-s+a,c=t+n,h=i+o,d=s+a;return le.apply(e,{positions:[c,h,d,l,h,d,l,u,d,c,u,d,c,h,d,c,u,d,c,u,A,c,h,A,c,h,d,c,h,A,l,h,A,l,h,d,l,h,d,l,h,A,l,u,A,l,u,d,l,u,A,c,u,A,c,u,d,l,u,d,c,u,A,l,u,A,l,h,A,c,h,A],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}var Si=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),s=t.call(this,e,r),se.memory.materials++,s}return C(i,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),se.memory.materials--}}]),i}(),Ti={opaque:0,mask:1,blend:2},Ri=["opaque","mask","blend"],Li=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"PhongMaterial",ambient:$.vec3([1,1,1]),diffuse:$.vec3([1,1,1]),specular:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.ambient=r.ambient,s.diffuse=r.diffuse,s.specular=r.specular,s.emissive=r.emissive,s.alpha=r.alpha,s.shininess=r.shininess,s.reflectivity=r.reflectivity,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,r.ambientMap&&(s._ambientMap=s._checkComponent("Texture",r.ambientMap)),r.diffuseMap&&(s._diffuseMap=s._checkComponent("Texture",r.diffuseMap)),r.specularMap&&(s._specularMap=s._checkComponent("Texture",r.specularMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.reflectivityMap&&(s._reflectivityMap=s._checkComponent("Texture",r.reflectivityMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.diffuseFresnel&&(s._diffuseFresnel=s._checkComponent("Fresnel",r.diffuseFresnel)),r.specularFresnel&&(s._specularFresnel=s._checkComponent("Fresnel",r.specularFresnel)),r.emissiveFresnel&&(s._emissiveFresnel=s._checkComponent("Fresnel",r.emissiveFresnel)),r.alphaFresnel&&(s._alphaFresnel=s._checkComponent("Fresnel",r.alphaFresnel)),r.reflectivityFresnel&&(s._reflectivityFresnel=s._checkComponent("Fresnel",r.reflectivityFresnel)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return Ri[this._state.alphaMode]},set:function(e){var t=Ti[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ui={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},Oi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),s._preset="default",r.preset?(s.preset=r.preset,void 0!==r.fill&&(s.fill=r.fill),r.fillColor&&(s.fillColor=r.fillColor),void 0!==r.fillAlpha&&(s.fillAlpha=r.fillAlpha),void 0!==r.edges&&(s.edges=r.edges),r.edgeColor&&(s.edgeColor=r.edgeColor),void 0!==r.edgeAlpha&&(s.edgeAlpha=r.edgeAlpha),void 0!==r.edgeWidth&&(s.edgeWidth=r.edgeWidth),void 0!==r.backfaces&&(s.backfaces=r.backfaces),void 0!==r.glowThrough&&(s.glowThrough=r.glowThrough)):(s.fill=r.fill,s.fillColor=r.fillColor,s.fillAlpha=r.fillAlpha,s.edges=r.edges,s.edgeColor=r.edgeColor,s.edgeAlpha=r.edgeAlpha,s.edgeWidth=r.edgeWidth,s.backfaces=r.backfaces,s.glowThrough=r.glowThrough),s}return C(i,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return Ui}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ui[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ui).join(", "))}}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ni={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},Qi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),s._preset="default",r.preset?(s.preset=r.preset,r.edgeColor&&(s.edgeColor=r.edgeColor),void 0!==r.edgeAlpha&&(s.edgeAlpha=r.edgeAlpha),void 0!==r.edgeWidth&&(s.edgeWidth=r.edgeWidth)):(s.edgeColor=r.edgeColor,s.edgeAlpha=r.edgeAlpha,s.edgeWidth=r.edgeWidth),s.edges=!1!==r.edges,s}return C(i,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return Ni}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ni[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ni).join(", "))}}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Hi={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},Vi=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._units="meters",s._scale=1,s._origin=$.vec3([0,0,0]),s.units=r.units,s.scale=r.scale,s.origin=r.origin,s}return C(i,[{key:"unitsInfo",get:function(){return Hi}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),Hi[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),i}(),ji=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._supported=mt.SUPPORTED_EXTENSIONS.OES_standard_derivatives,s.enabled=r.enabled,s.kernelRadius=r.kernelRadius,s.intensity=r.intensity,s.bias=r.bias,s.scale=r.scale,s.minResolution=r.minResolution,s.numSamples=r.numSamples,s.blur=r.blur,s.blendCutoff=r.blendCutoff,s.blendFactor=r.blendFactor,s}return C(i,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this)}}]),i}(),Gi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},zi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),r.preset?(s.preset=r.preset,void 0!==r.pointSize&&(s.pointSize=r.pointSize),void 0!==r.roundPoints&&(s.roundPoints=r.roundPoints),void 0!==r.perspectivePoints&&(s.perspectivePoints=r.perspectivePoints),void 0!==r.minPerspectivePointSize&&(s.minPerspectivePointSize=r.minPerspectivePointSize),void 0!==r.maxPerspectivePointSize&&(s.maxPerspectivePointSize=r.minPerspectivePointSize)):(s._preset="default",s.pointSize=r.pointSize,s.roundPoints=r.roundPoints,s.perspectivePoints=r.perspectivePoints,s.minPerspectivePointSize=r.minPerspectivePointSize,s.maxPerspectivePointSize=r.maxPerspectivePointSize),s.filterIntensity=r.filterIntensity,s.minIntensity=r.minIntensity,s.maxIntensity=r.maxIntensity,s}return C(i,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return Gi}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Gi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Gi).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ki={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},Wi=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"LinesMaterial",lineWidth:null}),r.preset?(s.preset=r.preset,void 0!==r.lineWidth&&(s.lineWidth=r.lineWidth)):(s._preset="default",s.lineWidth=r.lineWidth),s}return C(i,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Ki}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ki[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ki).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function Xi(e,t){for(var i,s,r={},n=0,o=t.length;n1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),s=t.call(this,null,r);var n=r.canvasElement||document.getElementById(r.canvasId);if(!(n instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";s._tickifiedFunctions={};var o=!!r.transparent,a=!!r.alphaDepthMask;return s._aabbDirty=!0,s.viewer=e,s.occlusionTestCountdown=0,s.loading=0,s.startTime=(new Date).getTime(),s.models={},s.objects={},s._numObjects=0,s.visibleObjects={},s._numVisibleObjects=0,s.xrayedObjects={},s._numXRayedObjects=0,s.highlightedObjects={},s._numHighlightedObjects=0,s.selectedObjects={},s._numSelectedObjects=0,s.colorizedObjects={},s._numColorizedObjects=0,s.opacityObjects={},s._numOpacityObjects=0,s.offsetObjects={},s._numOffsetObjects=0,s._modelIds=null,s._objectIds=null,s._visibleObjectIds=null,s._xrayedObjectIds=null,s._highlightedObjectIds=null,s._selectedObjectIds=null,s._colorizedObjectIds=null,s._opacityObjectIds=null,s._offsetObjectIds=null,s._collidables={},s._compilables={},s._needRecompile=!1,s.types={},s.components={},s.sectionPlanes={},s.lights={},s.lightMaps={},s.reflectionMaps={},s.bitmaps={},s.lineSets={},s.realWorldOffset=r.realWorldOffset||new Float64Array([0,0,0]),s.canvas=new vt(b(s),{dontClear:!0,canvas:n,spinnerElementId:r.spinnerElementId,transparent:o,webgl2:!1!==r.webgl2,contextAttr:r.contextAttr||{},backgroundColor:r.backgroundColor,backgroundColorFromAmbientLight:r.backgroundColorFromAmbientLight,premultipliedAlpha:r.premultipliedAlpha}),s.canvas.on("boundary",(function(){s.glRedraw()})),s.canvas.on("webglContextFailed",(function(){alert("xeokit failed to find WebGL!")})),s._renderer=new Kt(b(s),{transparent:o,alphaDepthMask:a}),s._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;var e=null;this.getHash=function(){if(e)return e;var t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";for(var i=[],s=0,r=t;sthis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},s._sectionPlanesState.setNumCachedSectionPlanes(r.numCachedSectionPlanes||0),s._lightsState=new function(){var e=$.vec4([0,0,0,0]),t=$.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];var i=null,s=null;this.getHash=function(){if(i)return i;for(var e,t=[],s=this.lights,r=0,n=s.length;r0&&t.push("/lm"),this.reflectionMaps.length>0&&t.push("/rm"),t.push(";"),i=t.join("")},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(var t=0,r=this.lights.length;t1&&void 0!==arguments[1])||arguments[1];e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}},{key:"_deRegisterVisibleObject",value:function(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}},{key:"_objectXRayedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}},{key:"_deRegisterXRayedObject",value:function(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}},{key:"_objectHighlightedUpdated",value:function(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}},{key:"_deRegisterHighlightedObject",value:function(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}},{key:"_objectSelectedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}},{key:"_deRegisterSelectedObject",value:function(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}},{key:"_objectColorizeUpdated",value:function(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}},{key:"_deRegisterColorizedObject",value:function(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}},{key:"_objectOpacityUpdated",value:function(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}},{key:"_deRegisterOpacityObject",value:function(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}},{key:"_objectOffsetUpdated",value:function(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}},{key:"_deRegisterOffsetObject",value:function(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}},{key:"_webglContextLost",value:function(){for(var e in this.canvas.spinner.processes++,this.components)if(this.components.hasOwnProperty(e)){var t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}},{key:"_webglContextRestored",value:function(){var e=this.canvas.gl;for(var t in this.components)if(this.components.hasOwnProperty(t)){var i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}},{key:"capabilities",get:function(){return this._renderer.capabilities}},{key:"entityOffsetsEnabled",get:function(){return this._entityOffsetsEnabled}},{key:"pickSurfacePrecisionEnabled",get:function(){return!1}},{key:"logarithmicDepthBufferEnabled",get:function(){return this._logarithmicDepthBufferEnabled}},{key:"numCachedSectionPlanes",get:function(){return this._sectionPlanesState.getNumCachedSectionPlanes()},set:function(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}},{key:"pbrEnabled",get:function(){return this._pbrEnabled},set:function(e){this._pbrEnabled=!!e,this.glRedraw()}},{key:"dtxEnabled",get:function(){return this._dtxEnabled},set:function(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled},set:function(e){this._colorTextureEnabled=!!e,this.glRedraw()}},{key:"doOcclusionTest",value:function(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}},{key:"render",value:function(e){e&&_e.runTasks();var t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;var i,s,r=this._passes,n=this._clearEachPass;for(i=0;in&&(n=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),u=!0}u||(i=-100,s=-100,r=-100,n=100,o=100,a=100),this._aabb[0]=i,this._aabb[1]=s,this._aabb[2]=r,this._aabb[3]=n,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}},{key:"_setAABBDirty",value:function(){this._aabbDirty=!0,this.fire("boundary")}},{key:"pick",value:function(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");var i=e.includeEntities||e.include;i&&(e.includeEntityIds=Xi(this,i));var s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=Xi(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}},{key:"snapPick",value:function(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}},{key:"clear",value:function(){var e;for(var t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}},{key:"clearLights",value:function(){for(var e=Object.keys(this.lights),t=0,i=e.length;to&&(o=t[3]),t[4]>a&&(a=t[4]),t[5]>l&&(l=t[5]),i=!0}})),i){var u=$.AABB3();return u[0]=s,u[1]=r,u[2]=n,u[3]=o,u[4]=a,u[5]=l,u}return this.aabb}},{key:"setObjectsVisible",value:function(e,t){return this.withObjects(e,(function(e){var i=e.visible!==t;return e.visible=t,i}))}},{key:"setObjectsCollidable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.collidable!==t;return e.collidable=t,i}))}},{key:"setObjectsCulled",value:function(e,t){return this.withObjects(e,(function(e){var i=e.culled!==t;return e.culled=t,i}))}},{key:"setObjectsSelected",value:function(e,t){return this.withObjects(e,(function(e){var i=e.selected!==t;return e.selected=t,i}))}},{key:"setObjectsHighlighted",value:function(e,t){return this.withObjects(e,(function(e){var i=e.highlighted!==t;return e.highlighted=t,i}))}},{key:"setObjectsXRayed",value:function(e,t){return this.withObjects(e,(function(e){var i=e.xrayed!==t;return e.xrayed=t,i}))}},{key:"setObjectsEdges",value:function(e,t){return this.withObjects(e,(function(e){var i=e.edges!==t;return e.edges=t,i}))}},{key:"setObjectsColorized",value:function(e,t){return this.withObjects(e,(function(e){e.colorize=t}))}},{key:"setObjectsOpacity",value:function(e,t){return this.withObjects(e,(function(e){var i=e.opacity!==t;return e.opacity=t,i}))}},{key:"setObjectsPickable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.pickable!==t;return e.pickable=t,i}))}},{key:"setObjectsOffset",value:function(e,t){this.withObjects(e,(function(e){e.offset=t}))}},{key:"withObjects",value:function(e,t){le.isString(e)&&(e=[e]);for(var i=!1,s=0,r=e.length;ss&&(s=r,e.apply(void 0,A(i)))}));return this._tickifiedFunctions[t]={tickSubId:o,wrapperFunc:n},n}},{key:"destroy",value:function(){for(var e in f(B(i.prototype),"destroy",this).call(this),this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}]),i}(),Yi=1e3,Zi=1001,qi=1002,$i=1003,es=1004,ts=1004,is=1005,ss=1005,rs=1006,ns=1007,os=1007,as=1008,ls=1008,us=1009,As=1010,cs=1011,hs=1012,ds=1013,ps=1014,fs=1015,vs=1016,gs=1017,ms=1018,_s=1020,ys=1021,bs=1022,Bs=1023,xs=1024,ws=1025,Ps=1026,Cs=1027,Ms=1028,Fs=1029,Es=1030,ks=1031,Is=1033,Ds=33776,Ss=33777,Ts=33778,Rs=33779,Ls=35840,Us=35841,Os=35842,Ns=35843,Qs=36196,Hs=37492,Vs=37496,js=37808,Gs=37809,zs=37810,Ks=37811,Ws=37812,Xs=37813,Js=37814,Ys=37815,Zs=37816,qs=37817,$s=37818,er=37819,tr=37820,ir=37821,sr=36492,rr=3e3,nr=3001,or=1e4,ar=10001,lr=10002,ur=10003,Ar=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){var t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,n=e._state.billboard,o=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,u=[];u.push("#version 300 es"),u.push("// Lambertian drawing vertex shader"),u.push("in vec3 position;"),u.push("uniform mat4 modelMatrix;"),u.push("uniform mat4 viewMatrix;"),u.push("uniform mat4 projMatrix;"),u.push("uniform vec4 colorize;"),u.push("uniform vec3 offset;"),l&&u.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(u.push("uniform float logDepthBufFC;"),u.push("out float vFragDepth;"),u.push("bool isPerspectiveMatrix(mat4 m) {"),u.push(" return (m[2][3] == - 1.0);"),u.push("}"),u.push("out float isPerspective;"));a&&u.push("out vec4 vWorldPosition;");if(u.push("uniform vec4 lightAmbient;"),u.push("uniform vec4 materialColor;"),u.push("uniform vec3 materialEmissive;"),r.normalsBuf){u.push("in vec3 normal;"),u.push("uniform mat4 modelNormalMatrix;"),u.push("uniform mat4 viewNormalMatrix;");for(var A=0,c=s.lights.length;A= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),u.push(" }"),u.push(" return normalize(v);"),u.push("}"))}u.push("out vec4 vColor;"),"points"===r.primitiveName&&u.push("uniform float pointSize;");"spherical"!==n&&"cylindrical"!==n||(u.push("void billboard(inout mat4 mat) {"),u.push(" mat[0][0] = 1.0;"),u.push(" mat[0][1] = 0.0;"),u.push(" mat[0][2] = 0.0;"),"spherical"===n&&(u.push(" mat[1][0] = 0.0;"),u.push(" mat[1][1] = 1.0;"),u.push(" mat[1][2] = 0.0;")),u.push(" mat[2][0] = 0.0;"),u.push(" mat[2][1] = 0.0;"),u.push(" mat[2][2] =1.0;"),u.push("}"));u.push("void main(void) {"),u.push("vec4 localPosition = vec4(position, 1.0); "),u.push("vec4 worldPosition;"),l&&u.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?u.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):u.push("vec4 localNormal = vec4(normal, 0.0); "),u.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),u.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));u.push("mat4 viewMatrix2 = viewMatrix;"),u.push("mat4 modelMatrix2 = modelMatrix;"),o&&u.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(u.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),u.push("billboard(modelMatrix2);"),u.push("billboard(viewMatrix2);"),u.push("billboard(modelViewMatrix);"),r.normalsBuf&&(u.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),u.push("billboard(modelNormalMatrix2);"),u.push("billboard(viewNormalMatrix2);"),u.push("billboard(modelViewNormalMatrix);")),u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&u.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(u.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),u.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),u.push("float lambertian = 1.0;"),r.normalsBuf)for(var d=0,p=s.lights.length;d0,n=t.gammaOutput,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(var a=0,l=i.getNumAllocatedSectionPlanes();a 0.0) { discard; }"),o.push("}")}"points"===s.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)):(this.vertex=function(e){var t=e.scene;e._material;var i,s=e._state,r=t._sectionPlanesState,n=e._geometry._state,o=t._lightsState,a=s.billboard,l=s.background,u=s.stationary,A=function(e){if(!e._geometry._state.uvBuf)return!1;var t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=dr(e),h=r.getNumAllocatedSectionPlanes()>0,d=hr(e),p=!!n.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),h&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(var v=0,g=o.lights.length;v= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}A&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));n.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===n.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var m=0,_=o.lights.length;m<_;m++)o.lights[m].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+m+";"),f.push("uniform mat4 shadowProjMatrix"+m+";"),f.push("out vec4 vShadowPosFromLight"+m+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");c&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),u?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),c&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(c){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(var y=0,b=o.lights.length;y0,l=dr(e),u=s.uvBuf,A="PhongMaterial"===o.type,c="MetallicMaterial"===o.type,h="SpecularMaterial"===o.type,d=hr(e);t.gammaInput;var p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var v=0;v0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),n.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),A&&((n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = "+cr[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||h)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),n.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+cr[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(n.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));o.ambient&&f.push("uniform vec3 materialAmbient;");o.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==o.alpha&&null!==o.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");o.emissive&&f.push("uniform vec3 materialEmissive;");o.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==o.glossiness&&null!==o.glossiness&&f.push("uniform float materialGlossiness;");void 0!==o.shininess&&null!==o.shininess&&f.push("uniform float materialShininess;");o.specular&&f.push("uniform vec3 materialSpecular;");void 0!==o.metallic&&null!==o.metallic&&f.push("uniform float materialMetallic;");void 0!==o.roughness&&null!==o.roughness&&f.push("uniform float materialRoughness;");void 0!==o.specularF0&&null!==o.specularF0&&f.push("uniform float materialSpecularF0;");u&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));u&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));u&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));u&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&u&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&u&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&u&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));u&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));u&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&u&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&u&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&u&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(var g=0,m=n.lights.length;g 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),o.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");o.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):o.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");o.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");o.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==o.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==o.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==o.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==o.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==o.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));u&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+cr[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));u&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+cr[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));u&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+cr[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));u&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+cr[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));u&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));u&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(n.lights.length>0||n.lightMaps.length>0||n.reflectionMaps.length>0)){u&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),u&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),u&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),u&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),u&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),u&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),u&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),A&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),h&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),n.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),A&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(h||c)&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(var B=0,x=n.lights.length;B0)for(var f=s._sectionPlanesState.sectionPlanes,v=t.renderFlags,g=0;g0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(A=0,c=n.sectionPlanes.length;A0&&n.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,n.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),n.reflectionMaps.length>0&&n.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,n.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),this._uGammaFactor&&r.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};var mr=C((function e(t){w(this,e),this.vertex=function(e){var t=e.scene,i=t._lightsState,s=function(e){var t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,n=!!e._geometry._state.compressGeometry,o=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),n&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(var u=0,A=i.lights.length;u= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===o||"cylindrical"===o)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===o&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),n&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(n?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(var h=0,d=i.lights.length;h0,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));s&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}"points"===e._geometry._state.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var _r=new Q({}),yr=$.vec3(),br=function(e,t){this.id=_r.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new mr(t),this._allocate(t)},Br={};br.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Br[t];return i||(i=new br(t,e),Br[t]=i,se.memory.programs++),i._useCount++,i},br.prototype.put=function(){0==--this._useCount&&(_r.removeItem(this.id),this._program&&this._program.destroy(),delete Br[this._hash],se.memory.programs--)},br.prototype.webglContextRestored=function(){this._program=null},br.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var s=this._scene,r=s.camera,n=s.canvas.gl,o=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(a.originHash,u):r.viewMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){var A=s._sectionPlanesState.getNumAllocatedSectionPlanes(),c=s._sectionPlanesState.sectionPlanes.length;if(A>0)for(var h=s._sectionPlanesState.sectionPlanes,d=t.renderFlags,p=0;p0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Edges drawing vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));o.push("vColor = edgeColor;"),i&&o.push("vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));s&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var wr=new Q({}),Pr=$.vec3(),Cr=function(e,t){this.id=wr.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new xr(t),this._allocate(t)},Mr={};Cr.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Mr[t];return i||(i=new Cr(t,e),Mr[t]=i,se.memory.programs++),i._useCount++,i},Cr.prototype.put=function(){0==--this._useCount&&(wr.removeItem(this.id),this._program&&this._program.destroy(),delete Mr[this._hash],se.memory.programs--)},Cr.prototype.webglContextRestored=function(){this._program=null},Cr.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var s,r,n=this._scene,o=n.camera,a=n.canvas.gl,l=t._state,u=t._geometry,A=u._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):o.viewMatrix),l.clippable){var h=n._sectionPlanesState.getNumAllocatedSectionPlanes(),d=n._sectionPlanesState.sectionPlanes.length;if(h>0)for(var p=n._sectionPlanesState.sectionPlanes,f=t.renderFlags,v=0;v0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh picking vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("out vec4 vViewPosition;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("uniform vec2 pickClipPos;"),o.push("vec4 remapClipPos(vec4 clipPos) {"),o.push(" clipPos.xy /= clipPos.w;"),o.push(" clipPos.xy -= pickClipPos;"),o.push(" clipPos.xy *= clipPos.w;"),o.push(" return clipPos;"),o.push("}"),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"));o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = remapClipPos(clipPos);"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(t)}));var Er=$.vec3(),kr=function(e,t){this._hash=e,this._shaderSource=new Fr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ir={};kr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),i=Ir[t];if(!i){if((i=new kr(t,e)).errors)return console.log(i.errors.join("\n")),null;Ir[t]=i,se.memory.programs++}return i._useCount++,i},kr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ir[this._hash],se.memory.programs--)},kr.prototype.webglContextRestored=function(){this._program=null},kr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._state,n=t._material._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){var l=i._sectionPlanesState.getNumAllocatedSectionPlanes(),u=i._sectionPlanesState.sectionPlanes.length;if(l>0)for(var A=i._sectionPlanesState.sectionPlanes,c=t.renderFlags,h=0;h>24&255,b=_>>16&255,B=_>>8&255,x=255&_;s.uniform4f(this._uPickColor,x/255,B/255,b/255,y/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),o.indicesBuf?(s.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&s.drawArrays(s.TRIANGLES,0,o.positions.numItems)},kr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Ft(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=t._sectionPlanesState.sectionPlanes.length;r0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(t)}));var Sr=$.vec3(),Tr=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Dr(t),this._allocate(t)},Rr={};Tr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Rr[t];if(!i){if((i=new Tr(t,e)).errors)return console.log(i.errors.join("\n")),null;Rr[t]=i,se.memory.programs++}return i._useCount++,i},Tr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Rr[this._hash],se.memory.programs--)},Tr.prototype.webglContextRestored=function(){this._program=null},Tr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._state,n=t._material._state,o=t._geometry,a=t._geometry._state,l=t.origin,u=n.backfaces,A=n.frontface,c=i.camera.project,h=o._getPickTrianglePositions(),d=o._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){var p=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){var f=i._sectionPlanesState.getNumAllocatedSectionPlanes(),v=i._sectionPlanesState.sectionPlanes.length;if(f>0)for(var g=i._sectionPlanesState.sectionPlanes,m=t.renderFlags,_=0;_0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh occlusion vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(t)}));var Ur=$.vec3(),Or=function(e,t){this._hash=e,this._shaderSource=new Lr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Nr={};Or.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";"),i=Nr[t];if(!i){if((i=new Or(t,e)).errors)return console.log(i.errors.join("\n")),null;Nr[t]=i,se.memory.programs++}return i._useCount++,i},Or.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Nr[this._hash],se.memory.programs--)},Or.prototype.webglContextRestored=function(){this._program=null},Or.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._material._state,n=t._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){var l=r.backfaces;e.backfaces!==l&&(l?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=l);var u=r.frontface;e.frontface!==u&&(u?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=u),this._lastMaterialId=r.id}var A=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(n.originHash,a):A.viewMatrix),n.clippable){var c=i._sectionPlanesState.getNumAllocatedSectionPlanes(),h=i._sectionPlanesState.sectionPlanes.length;if(c>0)for(var d=i._sectionPlanesState.sectionPlanes,p=t.renderFlags,f=0;f0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(t),this.fragment=function(e){var t=e.scene;t.canvas.gl;var i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(t)}));var Hr=function(e,t){this._hash=e,this._shaderSource=new Qr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Vr={};Hr.get=function(e){var t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),s=Vr[i];if(!s){if((s=new Hr(i,e)).errors)return console.log(s.errors.join("\n")),null;Vr[i]=s,se.memory.programs++}return s._useCount++,s},Hr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Vr[this._hash],se.memory.programs--)},Hr.prototype.webglContextRestored=function(){this._program=null},Hr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){var n=s.backfaces;e.backfaces!==n&&(n?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=n);var o=s.frontface;e.frontface!==o&&(o?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=o),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){var a=t.vertexBufs;a.id!==this._lastVertexBufsId&&(a.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=a.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Hr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new Ft(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(var r=0,n=t._sectionPlanesState.sectionPlanes.length;r0)for(var r,n,o,a=0,l=this._uSectionPlanes.length;a1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r)).originalSystemId=r.originalSystemId||s.id,s.renderFlags=new jr,s._state=new Jt({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==r.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!r.stationary,background:!!r.background,billboard:s._checkBillboard(r.billboard),layer:null,colorize:null,pickID:s.scene._renderer.getPickID(b(s)),drawHash:"",pickHash:"",offset:$.vec3(),origin:null,originHash:null}),s._drawRenderer=null,s._shadowRenderer=null,s._emphasisFillRenderer=null,s._emphasisEdgesRenderer=null,s._pickMeshRenderer=null,s._pickTriangleRenderer=null,s._occlusionRenderer=null,s._geometry=r.geometry?s._checkComponent2(["ReadableGeometry","VBOGeometry"],r.geometry):s.scene.geometry,s._material=r.material?s._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],r.material):s.scene.material,s._xrayMaterial=r.xrayMaterial?s._checkComponent("EmphasisMaterial",r.xrayMaterial):s.scene.xrayMaterial,s._highlightMaterial=r.highlightMaterial?s._checkComponent("EmphasisMaterial",r.highlightMaterial):s.scene.highlightMaterial,s._selectedMaterial=r.selectedMaterial?s._checkComponent("EmphasisMaterial",r.selectedMaterial):s.scene.selectedMaterial,s._edgeMaterial=r.edgeMaterial?s._checkComponent("EdgeMaterial",r.edgeMaterial):s.scene.edgeMaterial,s._parentNode=null,s._aabb=null,s._aabbDirty=!0,s._numTriangles=s._geometry?s._geometry.numTriangles:0,s.scene._aabbDirty=!0,s._scale=$.vec3(),s._quaternion=$.identityQuaternion(),s._rotation=$.vec3(),s._position=$.vec3(),s._worldMatrix=$.identityMat4(),s._worldNormalMatrix=$.identityMat4(),s._localMatrixDirty=!0,s._worldMatrixDirty=!0,s._worldNormalMatrixDirty=!0;var n=r.origin||r.rtcCenter;if(n&&(s._state.origin=$.vec3(n),s._state.originHash=n.join()),r.matrix?s.matrix=r.matrix:(s.scale=r.scale,s.position=r.position,r.quaternion||(s.rotation=r.rotation)),s._isObject=r.isObject,s._isObject&&s.scene._registerObject(b(s)),s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.layer=r.layer,s.colorize=r.colorize,s.opacity=r.opacity,s.offset=r.offset,r.parentId){var o=s.scene.components[r.parentId];o?o.isNode?o.addChild(b(s)):s.error("Parent is not a Node: '"+r.parentId+"'"):s.error("Parent not found: '"+r.parentId+"'"),s._parentNode=o}else r.parent&&(r.parent.isNode||s.error("Parent is not a Node"),r.parent.addChild(b(s)),s._parentNode=r.parent);return s.compile(),s}return C(i,[{key:"type",get:function(){return"Mesh"}},{key:"isMesh",get:function(){return!0}},{key:"parent",get:function(){return this._parentNode}},{key:"geometry",get:function(){return this._geometry}},{key:"material",get:function(){return this._material}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=$.identityMat4()),$.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix},set:function(e){this.__localMatrix||(this.__localMatrix=$.identityMat4()),this.__localMatrix.set(e||$r),$.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._aabbDirty&&this._updateAABB(),this._aabb}},{key:"origin",get:function(){return this._state.origin},set:function(e){e?(this._state.origin||(this._state.origin=$.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"rtcCenter",get:function(){return this.origin},set:function(e){this.origin=e}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._state.visible},set:function(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}},{key:"xrayed",get:function(){return this._state.xrayed},set:function(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}},{key:"highlighted",get:function(){return this._state.highlighted},set:function(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}},{key:"selected",get:function(){return this._state.selected},set:function(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}},{key:"culled",get:function(){return this._state.culled},set:function(e){this._state.culled=!!e,this.glRedraw()}},{key:"clippable",get:function(){return this._state.clippable},set:function(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}},{key:"collidable",get:function(){return this._state.collidable},set:function(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"pickable",get:function(){return this._state.pickable},set:function(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._state.receivesShadow},set:function(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}},{key:"saoEnabled",get:function(){return!1}},{key:"colorize",get:function(){return this._state.colorize},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);var i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}},{key:"opacity",get:function(){return this._state.colorize[3]},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1);var i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}},{key:"transparent",get:function(){return 2===this._material.alphaMode||this._state.colorize[3]<1}},{key:"layer",get:function(){return this._state.layer},set:function(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}},{key:"stationary",get:function(){return this._state.stationary}},{key:"billboard",get:function(){return this._state.billboard}},{key:"offset",get:function(){return this._state.offset},set:function(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!0}},{key:"xrayMaterial",get:function(){return this._xrayMaterial}},{key:"highlightMaterial",get:function(){return this._highlightMaterial}},{key:"selectedMaterial",get:function(){return this._selectedMaterial}},{key:"edgeMaterial",get:function(){return this._edgeMaterial}},{key:"_checkBillboard",value:function(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}},{key:"compile",value:function(){var e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=vr.get(this),this._emphasisFillRenderer=br.get(this),this._emphasisEdgesRenderer=Cr.get(this));var t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=kr.get(this)),this._state.occluder){var i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=Or.get(this))}}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}},{key:"_setWorldMatrixDirty",value:function(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentNode)$.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t0)for(var i=0;i-1){var R=k.geometry._state,L=k.scene,U=L.camera,O=L.canvas;if("triangles"===R.primitiveName){S.primitive="triangle";var N,Q,H,V=T,j=R.indices,G=R.positions;if(j){var z=j[V+0],K=j[V+1],W=j[V+2];n[0]=z,n[1]=K,n[2]=W,S.indices=n,N=3*z,Q=3*K,H=3*W}else H=(Q=(N=3*V)+3)+3;if(i[0]=G[N+0],i[1]=G[N+1],i[2]=G[N+2],s[0]=G[Q+0],s[1]=G[Q+1],s[2]=G[Q+2],r[0]=G[H+0],r[1]=G[H+1],r[2]=G[H+2],R.compressGeometry){var X=R.positionsDecodeMatrix;X&&(Fi.decompressPosition(i,X,i),Fi.decompressPosition(s,X,s),Fi.decompressPosition(r,X,r))}S.canvasPos?$.canvasPosToLocalRay(O.canvas,k.origin?Te(I,k.origin):I,D,k.worldMatrix,S.canvasPos,e,t):S.origin&&S.direction&&$.worldRayToLocalRay(k.worldMatrix,S.origin,S.direction,e,t),$.normalizeVec3(t),$.rayPlaneIntersect(e,t,i,s,r,o),S.localPos=o,S.position=o,v[0]=o[0],v[1]=o[1],v[2]=o[2],v[3]=1,$.transformVec4(k.worldMatrix,v,g),a[0]=g[0],a[1]=g[1],a[2]=g[2],S.canvasPos&&k.origin&&(a[0]+=k.origin[0],a[1]+=k.origin[1],a[2]+=k.origin[2]),S.worldPos=a,$.transformVec4(U.matrix,g,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],S.viewPos=l,$.cartesianToBarycentric(o,i,s,r,u),S.bary=u;var J=R.normals;if(J){if(R.compressGeometry){var Y=3*z,Z=3*K,q=3*W;Fi.decompressNormal(J.subarray(Y,Y+2),A),Fi.decompressNormal(J.subarray(Z,Z+2),c),Fi.decompressNormal(J.subarray(q,q+2),h)}else A[0]=J[N],A[1]=J[N+1],A[2]=J[N+2],c[0]=J[Q],c[1]=J[Q+1],c[2]=J[Q+2],h[0]=J[H],h[1]=J[H+1],h[2]=J[H+2];var ee=$.addVec3($.addVec3($.mulVec3Scalar(A,u[0],_),$.mulVec3Scalar(c,u[1],y),b),$.mulVec3Scalar(h,u[2],B),x);S.worldNormal=$.normalizeVec3($.transformVec3(k.worldNormalMatrix,ee,w))}var te=R.uv;if(te){if(d[0]=te[2*z],d[1]=te[2*z+1],p[0]=te[2*K],p[1]=te[2*K+1],f[0]=te[2*W],f[1]=te[2*W+1],R.compressGeometry){var ie=R.uvDecodeMatrix;ie&&(Fi.decompressUV(d,ie,d),Fi.decompressUV(p,ie,p),Fi.decompressUV(f,ie,f))}S.uv=$.addVec3($.addVec3($.mulVec2Scalar(d,u[0],P),$.mulVec2Scalar(p,u[1],C),M),$.mulVec2Scalar(f,u[2],F),E)}}}}}();function sn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);var i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);var s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);var r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);var n=e.heightSegments||1;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n<1&&(n=1);var o,a,l,u,A,c,h,d,p,f,v,g=!!e.openEnded,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,B=s/2,x=s/n,w=2*Math.PI/r,P=1/r,C=(t-i)/n,M=[],F=[],E=[],k=[],I=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(o=0;o<=n;o++)for(A=t-o*C,c=B-o*x,a=0;a<=r;a++)l=Math.sin(a*w),u=Math.cos(a*w),F.push(A*l),F.push(I),F.push(A*u),E.push(a*P),E.push(1*o/n),M.push(A*l+_),M.push(c+y),M.push(A*u+b);for(o=0;o0){for(p=M.length/3,F.push(0),F.push(1),F.push(0),E.push(.5),E.push(.5),M.push(0+_),M.push(B+y),M.push(0+b),a=0;a<=r;a++)l=Math.sin(a*w),u=Math.cos(a*w),f=.5*Math.sin(a*w)+.5,v=.5*Math.cos(a*w)+.5,F.push(t*l),F.push(1),F.push(t*u),E.push(f),E.push(v),M.push(t*l+_),M.push(B+y),M.push(t*u+b);for(a=0;a0){for(p=M.length/3,F.push(0),F.push(-1),F.push(0),E.push(.5),E.push(.5),M.push(0+_),M.push(0-B+y),M.push(0+b),a=0;a<=r;a++)l=Math.sin(a*w),u=Math.cos(a*w),f=.5*Math.sin(a*w)+.5,v=.5*Math.cos(a*w)+.5,F.push(i*l),F.push(-1),F.push(i*u),E.push(f),E.push(v),M.push(i*l+_),M.push(0-B+y),M.push(i*u+b);for(a=0;a0&&void 0!==arguments[0]?arguments[0]:{},t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0,n=e.radius||1;n<0&&(console.error("negative radius not allowed - will invert"),n*=-1);var o=e.heightSegments||18;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),(o=Math.floor(t*o))<18&&(o=18);var a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);var l,u,A,c,h,d,p,f,v,g,m,_,y,b,B=[],x=[],w=[],P=[];for(l=0;l<=o;l++)for(A=l*Math.PI/o,c=Math.sin(A),h=Math.cos(A),u=0;u<=a;u++)d=2*u*Math.PI/a,p=Math.sin(d),f=Math.cos(d)*c,v=h,g=p*c,m=1-u/a,_=l/o,x.push(f),x.push(v),x.push(g),w.push(m),w.push(_),B.push(i+n*f),B.push(s+n*v),B.push(r+n*g);for(l=0;l":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function on(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],n=e.size||1,o=[],a=[],l=e.text;le.isNumeric(l)&&(l=""+l);for(var u,A,c,h,d,p,f,v,g,m=(l||"").split("\n"),_=0,y=0,b=.04,B=0;B1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({active:!0,pos:$.vec3(),dir:$.vec3(),dist:0}),s.active=r.active,s.pos=r.pos,s.dir=r.dir,s.scene._sectionPlaneCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"SectionPlane"}},{key:"active",get:function(){return this._state.active},set:function(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dist",get:function(){return this._state.dist}},{key:"flipDir",value:function(){var e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}},{key:"destroy",value:function(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),un=$.vec4(4),An=$.vec4(),cn=$.vec4(),hn=$.vec3([1,0,0]),dn=$.vec3([0,1,0]),pn=$.vec3([0,0,1]),fn=$.vec3(3),vn=$.vec3(3),gn=$.identityMat4(),mn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e,r))._parentNode=null,s._children=[],s._aabb=null,s._aabbDirty=!0,s.scene._aabbDirty=!0,s._numTriangles=0,s._scale=$.vec3(),s._quaternion=$.identityQuaternion(),s._rotation=$.vec3(),s._position=$.vec3(),s._offset=$.vec3(),s._localMatrix=$.identityMat4(),s._worldMatrix=$.identityMat4(),s._localMatrixDirty=!0,s._worldMatrixDirty=!0,r.matrix?s.matrix=r.matrix:(s.scale=r.scale,s.position=r.position,r.quaternion||(s.rotation=r.rotation)),s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s._isObject=r.isObject,s._isObject&&s.scene._registerObject(b(s)),s.origin=r.origin,s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.colorize=r.colorize,s.opacity=r.opacity,s.offset=r.offset,r.children)for(var n=r.children,o=0,a=n.length;o1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"LambertMaterial",ambient:$.vec3([1,1,1]),color:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),s.ambient=r.ambient,s.color=r.color,s.emissive=r.emissive,s.alpha=r.alpha,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s.backfaces=r.backfaces,s.frontface=r.frontface,s}return C(i,[{key:"type",get:function(){return"LambertMaterial"}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){var t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),yn={opaque:0,mask:1,blend:2},bn=["opaque","mask","blend"],Bn=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"MetallicMaterial",baseColor:$.vec4([1,1,1]),emissive:$.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.baseColor=r.baseColor,s.metallic=r.metallic,s.roughness=r.roughness,s.specularF0=r.specularF0,s.emissive=r.emissive,s.alpha=r.alpha,r.baseColorMap&&(s._baseColorMap=s._checkComponent("Texture",r.baseColorMap)),r.metallicMap&&(s._metallicMap=s._checkComponent("Texture",r.metallicMap)),r.roughnessMap&&(s._roughnessMap=s._checkComponent("Texture",r.roughnessMap)),r.metallicRoughnessMap&&(s._metallicRoughnessMap=s._checkComponent("Texture",r.metallicRoughnessMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"MetallicMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"baseColor",get:function(){return this._state.baseColor},set:function(e){var t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"baseColorMap",get:function(){return this._baseColorMap}},{key:"metallic",get:function(){return this._state.metallic},set:function(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}},{key:"metallicMap",get:function(){return this._attached.metallicMap}},{key:"roughness",get:function(){return this._state.roughness},set:function(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}},{key:"roughnessMap",get:function(){return this._attached.roughnessMap}},{key:"metallicRoughnessMap",get:function(){return this._attached.metallicRoughnessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._attached.emissiveMap}},{key:"occlusionMap",get:function(){return this._attached.occlusionMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._attached.alphaMap}},{key:"normalMap",get:function(){return this._attached.normalMap}},{key:"alphaMode",get:function(){return bn[this._state.alphaMode]},set:function(e){var t=yn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),xn={opaque:0,mask:1,blend:2},wn=["opaque","mask","blend"],Pn=function(e){g(i,Si);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({type:"SpecularMaterial",diffuse:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),specular:$.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.diffuse=r.diffuse,s.specular=r.specular,s.glossiness=r.glossiness,s.specularF0=r.specularF0,s.emissive=r.emissive,s.alpha=r.alpha,r.diffuseMap&&(s._diffuseMap=s._checkComponent("Texture",r.diffuseMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.specularMap&&(s._specularMap=s._checkComponent("Texture",r.specularMap)),r.glossinessMap&&(s._glossinessMap=s._checkComponent("Texture",r.glossinessMap)),r.specularGlossinessMap&&(s._specularGlossinessMap=s._checkComponent("Texture",r.specularGlossinessMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"SpecularMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specularMap",get:function(){return this._specularMap}},{key:"specularGlossinessMap",get:function(){return this._specularGlossinessMap}},{key:"glossiness",get:function(){return this._state.glossiness},set:function(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}},{key:"glossinessMap",get:function(){return this._glossinessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"normalMap",get:function(){return this._normalMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"alphaMode",get:function(){return wn[this._state.alphaMode]},set:function(e){var t=xn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function Cn(e,t){var i,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===s){var n=zt(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===n)return null;if(33776===r)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(null===(i=zt(e,"WEBGL_compressed_texture_s3tc")))return null;if(33776===r)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){var o=zt(e,"WEBGL_compressed_texture_pvrtc");if(null===o)return null;if(35840===r)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){var a=zt(e,"WEBGL_compressed_texture_etc1");return null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){var l=zt(e,"WEBGL_compressed_texture_etc");if(null===l)return null;if(37492===r)return 3001===s?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===s?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){var u=zt(e,"WEBGL_compressed_texture_astc");if(null===u)return null;if(37808===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:u.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:u.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:u.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:u.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:u.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:u.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:u.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:u.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:u.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:u.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:u.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:u.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:u.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:u.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){var A=zt(e,"EXT_texture_compression_bptc");if(null===A)return null;if(36492===r)return 3001===s?A.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:A.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}var Mn=new Uint8Array([0,0,0,1]),Fn=function(){function e(t){var i=t.gl,s=t.target,r=t.format,n=t.type,o=t.wrapS,a=t.wrapT,l=t.wrapR,u=t.encoding,A=t.preloadColor,c=t.premultiplyAlpha,h=t.flipY;w(this,e),this.gl=i,this.target=s||i.TEXTURE_2D,this.format=r||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!h,this.unpackAlignment=4,this.wrapS=o||1e3,this.wrapT=a||1e3,this.wrapR=l||1e3,this.encoding=u||3001,this.texture=i.createTexture(),A&&this.setPreloadColor(A),this.allocated=!0}return C(e,[{key:"setPreloadColor",value:function(e){e?(Mn[0]=Math.floor(255*e[0]),Mn[1]=Math.floor(255*e[1]),Mn[2]=Math.floor(255*e[2]),Mn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Mn[0]=0,Mn[1]=0,Mn[2]=0,Mn[3]=255);var t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP)for(var i=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z],s=0,r=i.length;s1&&void 0!==arguments[1]?arguments[1]:{},i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);var s=!1;i.bindTexture(this.target,this.texture);var r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);var n=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var o=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);var a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);var l=Cn(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(s=!0);var u=Cn(i,this.magFilter);u&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,u);var A=Cn(i,this.wrapS);A&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,A);var c=Cn(i,this.wrapT);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,c);var h=Cn(i,this.format,this.encoding),d=Cn(i,this.type),p=En(i,this.internalFormat,h,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(le.isArray(e))for(var f=e,v=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z],g=0,m=v.length;g1;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,this.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,this.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,r.NONE);var a=Cn(r,this.wrapS);a&&r.texParameteri(this.target,r.TEXTURE_WRAP_S,a);var l=Cn(r,this.wrapT);if(l&&r.texParameteri(this.target,r.TEXTURE_WRAP_T,l),this.type===r.TEXTURE_3D||this.type===r.TEXTURE_2D_ARRAY){var u=Cn(r,this.wrapR);u&&r.texParameteri(this.target,r.TEXTURE_WRAP_R,u),r.texParameteri(this.type,r.TEXTURE_WRAP_R,u)}o?(r.texParameteri(this.target,r.TEXTURE_MIN_FILTER,kn(r,this.minFilter)),r.texParameteri(this.target,r.TEXTURE_MAG_FILTER,kn(r,this.magFilter))):(r.texParameteri(this.target,r.TEXTURE_MIN_FILTER,Cn(r,this.minFilter)),r.texParameteri(this.target,r.TEXTURE_MAG_FILTER,Cn(r,this.magFilter)));var A=Cn(r,this.format,this.encoding),c=Cn(r,this.type),h=En(r,this.internalFormat,A,c,this.encoding,!1);r.texStorage2D(r.TEXTURE_2D,n,h,t[0].width,t[0].height);for(var d=0,p=t.length;d5&&void 0!==arguments[5]&&arguments[5];if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}var o=i;return i===e.RED&&(s===e.FLOAT&&(o=e.R32F),s===e.HALF_FLOAT&&(o=e.R16F),s===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RG&&(s===e.FLOAT&&(o=e.RG32F),s===e.HALF_FLOAT&&(o=e.RG16F),s===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(o=e.RGBA32F),s===e.HALF_FLOAT&&(o=e.RGBA16F),s===e.UNSIGNED_BYTE&&(o=3001===r&&!1===n?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)),o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||zt(e,"EXT_color_buffer_float"),o}function kn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function In(e){if(!Dn(e.width)||!Dn(e.height)){var t=document.createElement("canvas");t.width=Sn(e.width),t.height=Sn(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Dn(e){return 0==(e&e-1)}function Sn(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var Tn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({texture:new Fn({gl:s.scene.canvas.gl}),matrix:$.identityMat4(),hasMatrix:r.translate&&(0!==r.translate[0]||0!==r.translate[1])||!!r.rotate||r.scale&&(0!==r.scale[0]||0!==r.scale[1]),minFilter:s._checkMinFilter(r.minFilter),magFilter:s._checkMagFilter(r.magFilter),wrapS:s._checkWrapS(r.wrapS),wrapT:s._checkWrapT(r.wrapT),flipY:s._checkFlipY(r.flipY),encoding:s._checkEncoding(r.encoding)}),s._src=null,s._image=null,s._translate=$.vec2([0,0]),s._scale=$.vec2([1,1]),s._rotate=$.vec2([0,0]),s._matrixDirty=!1,s.translate=r.translate,s.scale=r.scale,s.rotate=r.rotate,r.src?s.src=r.src:r.image&&(s.image=r.image),se.memory.textures++,s}return C(i,[{key:"type",get:function(){return"Texture"}},{key:"_checkMinFilter",value:function(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}},{key:"_checkMagFilter",value:function(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}},{key:"_checkWrapS",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkWrapT",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this._state.texture=new Fn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}},{key:"_update",value:function(){var e,t,i=this._state;this._matrixDirty&&(0===this._translate[0]&&0===this._translate[1]||(e=$.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(t=$.scalingMat4v([this._scale[0],this._scale[1],1]),e=e?$.mulMat4(e,t):t),0!==this._rotate&&(t=$.rotationMat4v(.0174532925*this._rotate,[0,0,1]),e=e?$.mulMat4(e,t):t),e&&(i.matrix=e),this._matrixDirty=!1);this.glRedraw()}},{key:"image",get:function(){return this._image},set:function(e){this._image=In(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}},{key:"src",get:function(){return this._src},set:function(e){this.scene.loading++,this.scene.canvas.spinner.processes++;var t=this,i=new Image;i.onload=function(){i=In(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}},{key:"translate",get:function(){return this._translate},set:function(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}},{key:"rotate",get:function(){return this._rotate},set:function(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}},{key:"minFilter",get:function(){return this._state.minFilter}},{key:"magFilter",get:function(){return this._state.magFilter}},{key:"wrapS",get:function(){return this._state.wrapS}},{key:"wrapT",get:function(){return this._state.wrapT}},{key:"flipY",get:function(){return this._state.flipY}},{key:"encoding",get:function(){return this._state.encoding}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),se.memory.textures--}}]),i}(),Rn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._state=new Jt({edgeColor:$.vec3([0,0,0]),centerColor:$.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),s.edgeColor=r.edgeColor,s.centerColor=r.centerColor,s.edgeBias=r.edgeBias,s.centerBias=r.centerBias,s.power=r.power,s}return C(i,[{key:"type",get:function(){return"Fresnel"}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}},{key:"centerColor",get:function(){return this._state.centerColor},set:function(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}},{key:"edgeBias",get:function(){return this._state.edgeBias},set:function(e){this._state.edgeBias=e||0,this.glRedraw()}},{key:"centerBias",get:function(){return this._state.centerBias},set:function(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}},{key:"power",get:function(){return this._state.power},set:function(e){this._state.power=null!=e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ln=se.memory,Un=$.AABB3(),On=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r))._state=new Jt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),s._numTriangles=0,s._edgeThreshold=r.edgeThreshold||10,s._aabb=null,s._obb=$.OBB3();var n,o=s._state,a=s.scene.canvas.gl;switch(r.primitive=r.primitive||"triangles",r.primitive){case"points":o.primitive=a.POINTS,o.primitiveName=r.primitive;break;case"lines":o.primitive=a.LINES,o.primitiveName=r.primitive;break;case"line-loop":o.primitive=a.LINE_LOOP,o.primitiveName=r.primitive;break;case"line-strip":o.primitive=a.LINE_STRIP,o.primitiveName=r.primitive;break;case"triangles":o.primitive=a.TRIANGLES,o.primitiveName=r.primitive;break;case"triangle-strip":o.primitive=a.TRIANGLE_STRIP,o.primitiveName=r.primitive;break;case"triangle-fan":o.primitive=a.TRIANGLE_FAN,o.primitiveName=r.primitive;break;default:s.error("Unsupported value for 'primitive': '"+r.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),o.primitive=a.TRIANGLES,o.primitiveName=r.primitive}if(!r.positions)return s.error("Config expected: positions"),y(s);if(!r.indices)return s.error("Config expected: indices"),y(s);var l=r.positionsDecodeMatrix;if(l);else{var u=Fi.getPositionsBounds(r.positions),A=Fi.compressPositions(r.positions,u.min,u.max);n=A.quantized,o.positionsDecodeMatrix=A.decodeMatrix,o.positionsBuf=new Et(a,a.ARRAY_BUFFER,n,n.length,3,a.STATIC_DRAW),Ln.positions+=o.positionsBuf.numItems,$.positions3ToAABB3(r.positions,s._aabb),$.positions3ToAABB3(n,Un,o.positionsDecodeMatrix),$.AABB3ToOBB3(Un,s._obb)}if(r.colors){var c=r.colors.constructor===Float32Array?r.colors:new Float32Array(r.colors);o.colorsBuf=new Et(a,a.ARRAY_BUFFER,c,c.length,4,a.STATIC_DRAW),Ln.colors+=o.colorsBuf.numItems}if(r.uv){var h=Fi.getUVBounds(r.uv),d=Fi.compressUVs(r.uv,h.min,h.max),p=d.quantized;o.uvDecodeMatrix=d.decodeMatrix,o.uvBuf=new Et(a,a.ARRAY_BUFFER,p,p.length,2,a.STATIC_DRAW),Ln.uvs+=o.uvBuf.numItems}if(r.normals){var f=Fi.compressNormals(r.normals),v=o.compressGeometry;o.normalsBuf=new Et(a,a.ARRAY_BUFFER,f,f.length,3,a.STATIC_DRAW,v),Ln.normals+=o.normalsBuf.numItems}var g=r.indices.constructor===Uint32Array||r.indices.constructor===Uint16Array?r.indices:new Uint32Array(r.indices);o.indicesBuf=new Et(a,a.ELEMENT_ARRAY_BUFFER,g,g.length,1,a.STATIC_DRAW),Ln.indices+=o.indicesBuf.numItems;var m=bi(n,g,o.positionsDecodeMatrix,s._edgeThreshold);return s._edgeIndicesBuf=new Et(a,a.ELEMENT_ARRAY_BUFFER,m,m.length,1,a.STATIC_DRAW),"triangles"===s._state.primitiveName&&(s._numTriangles=r.indices.length/3),s._buildHash(),Ln.meshes++,s}return C(i,[{key:"type",get:function(){return"VBOGeometry"}},{key:"isVBOGeometry",get:function(){return!0}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"aabb",get:function(){return this._aabb}},{key:"obb",get:function(){return this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Ln.meshes--}}]),i}(),Nn={};function Qn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var n=Nn.parse.from3DS(e).edit.objects[0].mesh,o=n.vertices,a=n.uvt,l=n.indices;r.processes--,i(le.apply(t,{primitive:"triangles",positions:o,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function Hn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var n=Nn.parse.fromOBJ(e),o=Nn.edit.unwrap(n.i_verts,n.c_verts,3),a=Nn.edit.unwrap(n.i_norms,n.c_norms,3),l=Nn.edit.unwrap(n.i_uvt,n.c_uvt,2),u=new Int32Array(n.i_verts.length),A=0;A0?a:null,autoNormals:0===a.length,uv:l,indices:u}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function Vn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);var r=e.center,n=r?r[0]:0,o=r?r[1]:0,a=r?r[2]:0,l=-t+n,u=-i+o,A=-s+a,c=t+n,h=i+o,d=s+a;return le.apply(e,{primitive:"lines",positions:[l,u,A,l,u,d,l,h,A,l,h,d,c,u,A,c,u,d,c,h,A,c,h,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function jn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Vn({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function Gn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);var i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1);for(var s=(t=t||10)/(i=i||10),r=t/2,n=[],o=[],a=0,l=0,u=-r;l<=i;l++,u+=s)n.push(-r),n.push(0),n.push(u),n.push(r),n.push(0),n.push(u),n.push(u),n.push(0),n.push(-r),n.push(u),n.push(0),n.push(r),o.push(a++),o.push(a++),o.push(a++),o.push(a++);return le.apply(e,{primitive:"lines",positions:n,indices:o})}function zn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);var s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);var r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);var n,o,a,l,u,A,c,h=e.center,d=h?h[0]:0,p=h?h[1]:0,f=h?h[2]:0,v=t/2,g=i/2,m=Math.floor(s)||1,_=Math.floor(r)||1,y=m+1,b=_+1,B=t/m,x=i/_,w=new Float32Array(y*b*3),P=new Float32Array(y*b*3),C=new Float32Array(y*b*2),M=0,F=0;for(n=0;n65535?Uint32Array:Uint16Array)(m*_*6);for(n=0;n<_;n++)for(o=0;o0&&void 0!==arguments[0]?arguments[0]:{},t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;var i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);var s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);var r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);var n=e.arc||2*Math.PI;n<0&&(console.warn("negative arc not allowed - will invert"),n*=-1),n>360&&(n=360);var o,a,l,u,A,c,h,d,p,f,v,g,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,B=[],x=[],w=[],P=[];for(d=0;d<=r;d++)for(h=0;h<=s;h++)o=h/s*n,a=.785398+d/r*Math.PI*2,_=t*Math.cos(o),y=t*Math.sin(o),l=(t+i*Math.cos(a))*Math.cos(o),u=(t+i*Math.cos(a))*Math.sin(o),A=i*Math.sin(a),B.push(l+_),B.push(u+y),B.push(A+b),w.push(1-h/s),w.push(d/r),c=$.normalizeVec3($.subVec3([l,u,A],[_,y,b],[]),[]),x.push(c[0]),x.push(c[1]),x.push(c[2]);for(d=1;d<=r;d++)for(h=1;h<=s;h++)p=(s+1)*d+h-1,f=(s+1)*(d-1)+h-1,v=(s+1)*(d-1)+h,g=(s+1)*d+h,P.push(p),P.push(f),P.push(v),P.push(v),P.push(g),P.push(p);return le.apply(e,{positions:B,normals:x,uv:w,indices:P})}function Wn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";var t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";for(var i=[],s=0;s0&&void 0!==arguments[0]?arguments[0]:{},t=e.curve.getPoints(e.divisions).map((function(e){return A(e)})).flat();return Wn({id:e.id,points:t})}Nn.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},Nn.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(Nn.parse._buffToStr(e));window.location.href=i},Nn.clone=function(e){return JSON.parse(JSON.stringify(e))},Nn.bin={},Nn.bin.f=new Float32Array(1),Nn.bin.fb=new Uint8Array(Nn.bin.f.buffer),Nn.bin.rf=function(e,t){for(var i=Nn.bin.f,s=Nn.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Nn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Nn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Nn.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Nn.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Nn.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Nn.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Nn.parse={},Nn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),un&&(n=u),Ao&&(o=A)}return{min:{x:t,y:i,z:s},max:{x:r,y:n,z:o}}};var Jn=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._type=r.type||(r.src?r.src.split(".").pop():null)||"jpg",s._pos=$.vec3(r.pos||[0,0,0]),s._up=$.vec3(r.up||[0,1,0]),s._normal=$.vec3(r.normal||[0,0,1]),s._height=r.height||1,s._origin=$.vec3(),s._rtcPos=$.vec3(),s._imageSize=$.vec2(),s._texture=new Tn(b(s),{flipY:!0}),s._image=new Image,"jpg"!==s._type&&"png"!==s._type&&(s.error('Unsupported type - defaulting to "jpg"'),s._type="jpg"),s._node=new mn(b(s),{matrix:$.inverseMat4($.lookAtMat4v(s._pos,$.subVec3(s._pos,s._normal,$.mat4()),s._up,$.mat4())),children:[s._bitmapMesh=new en(b(s),{scale:[1,1,1],rotation:[-90,0,0],collidable:r.collidable,pickable:r.pickable,opacity:r.opacity,clippable:r.clippable,geometry:new Ii(b(s),zn({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Li(b(s),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:s._texture,emissiveMap:s._texture,backfaces:!0})})]}),r.image?s.image=r.image:r.src?s.src=r.src:r.imageData&&(s.imageData=r.imageData),s.scene._bitmapCreated(b(s)),s}return C(i,[{key:"visible",get:function(){return this._bitmapMesh.visible},set:function(e){this._bitmapMesh.visible=e}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}},{key:"src",get:function(){return this._image.src},set:function(e){var t=this;if(e)switch(this._image.onload=function(){t._texture.image=t._image,t._imageSize[0]=t._image.width,t._imageSize[1]=t._image.height,t._updateBitmapMeshScale()},this._image.src=e,e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}},{key:"imageData",get:function(){var e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")},set:function(e){var t=this;this._image.onload=function(){t._texture.image=image,t._imageSize[0]=image.width,t._imageSize[1]=image.height,t._updateBitmapMeshScale()},this._image.src=e}},{key:"type",get:function(){return this._type},set:function(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}},{key:"pos",get:function(){return this._pos}},{key:"normal",get:function(){return this._normal}},{key:"up",get:function(){return this._up}},{key:"height",get:function(){return this._height},set:function(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}},{key:"collidable",get:function(){return this._bitmapMesh.collidable},set:function(e){this._bitmapMesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._bitmapMesh.clippable},set:function(e){this._bitmapMesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._bitmapMesh.pickable},set:function(e){this._bitmapMesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._bitmapMesh.opacity},set:function(e){this._bitmapMesh.opacity=e}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._bitmapDestroyed(this)}},{key:"_updateBitmapMeshScale",value:function(){var e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}]),i}(),Yn=$.OBB3(),Zn=$.OBB3(),qn=$.OBB3(),$n=function(){function e(t,i,s,r,n,o){var a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0;w(this,e),this.model=t,this.object=null,this.parent=null,this.transform=n,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=i,this.obb=null,this._aabbLocal=null,this._aabbWorld=$.AABB3(),this._aabbWorldDirty=!1,this.layer=a,this.portionId=l,this._color=new Uint8Array([s[0],s[1],s[2],r]),this._colorize=new Uint8Array([s[0],s[1],s[2],r]),this._colorizing=!1,this._transparent=r<255,this.numTriangles=0,this.origin=null,this.entity=null,n&&n._addMesh(this)}return C(e,[{key:"_sceneModelDirty",value:function(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}},{key:"_updateMatrix",value:function(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}},{key:"_finalize",value:function(e){this.layer.initFlags(this.portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this.layer.setVisible(this.portionId,e,this._transparent)}},{key:"_setColor",value:function(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)}},{key:"_setColorize",value:function(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)}},{key:"_setOpacity",value:function(e,t){var i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}},{key:"_setOffset",value:function(e){this.layer.setOffset(this.portionId,e)}},{key:"_setHighlighted",value:function(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this.layer.setXRayed(this.portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this.layer.setSelected(this.portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this.layer.setEdges(this.portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this.layer.setClippable(this.portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this.layer.setCollidable(this.portionId,e)}},{key:"_setPickable",value:function(e){this.layer.setPickable(this.portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this.layer.setCulled(this.portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"getEachVertex",value:function(e){this.layer.getEachVertex(this.portionId,e)}},{key:"aabb",get:function(){if(this._aabbWorldDirty){if($.AABB3ToOBB3(this._aabbLocal,Yn),this.transform?($.transformOBB3(this.transform.worldMatrix,Yn,Zn),$.transformOBB3(this.model.worldMatrix,Zn,qn),$.OBB3ToAABB3(qn,this._aabbWorld)):($.transformOBB3(this.model.worldMatrix,Yn,Zn),$.OBB3ToAABB3(Zn,this._aabbWorld)),this.origin){var e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld},set:function(e){this._aabbLocal=e}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),eo=new(function(){function e(){w(this,e),this._uint8Arrays={},this._float32Arrays={}}return C(e,[{key:"_clear",value:function(){this._uint8Arrays={},this._float32Arrays={}}},{key:"getUInt8Array",value:function(e){var t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}},{key:"getFloat32Array",value:function(e){var t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}}]),e}()),to=0;function io(){return to++,eo}var so={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},ro=new Float32Array([1,1,1,1]),no=new Float32Array([0,0,0,1]),oo=$.vec4(),ao=$.vec3(),lo=$.vec3(),uo=$.mat4(),Ao=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=s.instancing,n=void 0!==r&&r,o=s.edges,a=void 0!==o&&o;w(this,e),this._scene=t,this._withSAO=i,this._instancing=n,this._edges=a,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}return C(e,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){return[""]}},{key:"_buildFragmentShader",value:function(){return[""]}},{key:"_addMatricesUniformBlockLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}},{key:"_addRemapClipPosLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(".concat(t,"));")),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}},{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"setSectionPlanesStateUniforms",value:function(e){var t=this._scene,i=t.canvas.gl,s=e.model,r=e.layerIndex,n=t._sectionPlanesState.getNumAllocatedSectionPlanes(),o=t._sectionPlanesState.sectionPlanes.length;if(n>0)for(var a=t._sectionPlanesState.sectionPlanes,l=r*o,u=s.renderFlags,A=0;A0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,l=e._sectionPlanesState.getNumAllocatedSectionPlanes();a3&&void 0!==arguments[3]?arguments[3]:{},r=s.colorUniform,n=void 0!==r&&r,o=s.incrementDrawState,a=void 0!==o&&o,l=mt.MAX_TEXTURE_IMAGE_UNITS,u=this._scene,A=u.canvas.gl,c=t._state,h=t.model,d=c.textureSet,p=c.origin,f=c.positionsDecodeMatrix,v=u._lightsState,g=u.pointsMaterial,m=h.scene.camera,_=m.viewNormalMatrix,y=m.project,b=e.pickViewMatrix||m.viewMatrix,B=h.position,x=h.rotationMatrix,w=h.rotationMatrixConjugate,P=h.worldNormalMatrix;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?A.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(c));var C=0,M=16;this._matricesUniformBlockBufferData.set(w,0);var F=0!==p[0]||0!==p[1]||0!==p[2],E=0!==B[0]||0!==B[1]||0!==B[2];if(F||E){var k=ao;if(F){var I=$.transformPoint3(x,p,lo);k[0]=I[0],k[1]=I[1],k[2]=I[2]}else k[0]=0,k[1]=0,k[2]=0;k[0]+=B[0],k[1]+=B[1],k[2]+=B[2],this._matricesUniformBlockBufferData.set(Te(b,k,uo),C+=M)}else this._matricesUniformBlockBufferData.set(b,C+=M);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,C+=M),this._matricesUniformBlockBufferData.set(f,C+=M),this._matricesUniformBlockBufferData.set(P,C+=M),this._matricesUniformBlockBufferData.set(_,C+=M),A.bindBuffer(A.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),A.bufferData(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,A.DYNAMIC_DRAW),A.bindBufferBase(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),A.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),u.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var D=2/(Math.log(e.pickZFar+1)/Math.LN2);A.uniform1f(this._uLogDepthBufFC,D)}this._uZFar&&A.uniform1f(this._uZFar,u.camera.project.far)}if(this._uPickInvisible&&A.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&A.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&A.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&A.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&A.uniform2f(this._uDrawingBufferSize,A.drawingBufferWidth,A.drawingBufferHeight),this._uUVDecodeMatrix&&A.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._uIntensityRange&&g.filterIntensity&&A.uniform2f(this._uIntensityRange,g.minIntensity,g.maxIntensity),this._uPointSize&&A.uniform1f(this._uPointSize,g.pointSize),this._uNearPlaneHeight){var S="ortho"===u.camera.projection?1:A.drawingBufferHeight/(2*Math.tan(.5*u.camera.perspective.fov*Math.PI/180));A.uniform1f(this._uNearPlaneHeight,S)}if(d){var T=d.colorTexture,R=d.metallicRoughnessTexture,L=d.emissiveTexture,U=d.normalsTexture,O=d.occlusionTexture;this._uColorMap&&T&&(this._program.bindTexture(this._uColorMap,T.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uMetallicRoughMap&&R&&(this._program.bindTexture(this._uMetallicRoughMap,R.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uEmissiveMap&&L&&(this._program.bindTexture(this._uEmissiveMap,L.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uNormalMap&&U&&(this._program.bindTexture(this._uNormalMap,U.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uAOMap&&O&&(this._program.bindTexture(this._uAOMap,O.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l)}if(v.reflectionMaps.length>0&&v.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,v.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),v.lightMaps.length>0&&v.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,v.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),this._withSAO){var N=u.sao,Q=N.possible;if(Q){var H=A.drawingBufferWidth,V=A.drawingBufferHeight;oo[0]=H,oo[1]=V,oo[2]=N.blendCutoff,oo[3]=N.blendFactor,A.uniform4fv(this._uSAOParams,oo),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++}}if(n){var j=this._edges?"edgeColor":"fillColor",G=this._edges?"edgeAlpha":"fillAlpha";if(i===so["".concat(this._edges?"EDGES":"SILHOUETTE","_XRAYED")]){var z=u.xrayMaterial._state,K=z[j],W=z[G];A.uniform4f(this._uColor,K[0],K[1],K[2],W)}else if(i===so["".concat(this._edges?"EDGES":"SILHOUETTE","_HIGHLIGHTED")]){var X=u.highlightMaterial._state,J=X[j],Y=X[G];A.uniform4f(this._uColor,J[0],J[1],J[2],Y)}else if(i===so["".concat(this._edges?"EDGES":"SILHOUETTE","_SELECTED")]){var Z=u.selectedMaterial._state,q=Z[j],ee=Z[G];A.uniform4f(this._uColor,q[0],q[1],q[2],ee)}else A.uniform4fv(this._uColor,this._edges?no:ro)}this._draw({state:c,frameCtx:e,incrementDrawState:a}),A.bindVertexArray(null)}}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null,se.memory.programs--}}]),e}(),co=function(e){g(i,Ao);var t=_(i);function i(e,s){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.edges,o=void 0!==n&&n;return w(this,i),t.call(this,e,s,{instancing:!1,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{var n=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,n,i.indicesBuf.itemType,o),r&&s.drawElements++}}}]),i}(),ho=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,s=t._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Triangles batching draw vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in float flags;"),t.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),r&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),t.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=s.lights.length;l0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}]),i}(),po=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,o=i.getNumAllocatedSectionPlanes();n> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var A=0,c=i.getNumAllocatedSectionPlanes();A 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var h=0,d=t.lights.length;h0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}]),i}(),vo=function(e){g(i,co);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!1,edges:!0})}return C(i)}(),go=function(e){g(i,vo);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),mo=function(e){g(i,vo);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),_o=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}]),i}(),yo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),bo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Bo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),xo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}]),i}(),wo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Po=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}]),i}(),Co=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Triangles batching quality draw vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.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);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),r&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),n.push("vFragDepth = 1.0 + clipPos.w;")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Triangles batching quality draw fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),o.push("uniform sampler2D uAOMap;"),o.push("in vec4 vViewPosition;"),o.push("in vec3 vViewNormal;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=s.lights.length;a0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=s.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Fo=function(e){g(i,co);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var o=0,a=s.getNumAllocatedSectionPlanes();o> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var c=0,h=s.getNumAllocatedSectionPlanes();c 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var d=0,p=i.lights.length;d0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ro=$.vec3(),Lo=$.vec3(),Uo=$.vec3(),Oo=$.vec3(),No=$.mat4(),Qo=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Ro;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Lo;if(l){var m=Uo;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,No),(f=Oo)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElements(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ho=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new fo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new _o(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new yo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new To(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Qo(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new ho(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new ho(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new po(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new po(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Fo(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Fo(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new Co(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Co(this._scene,!0)),this._pbrRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fo(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new xo(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new wo(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new go(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new mo(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new _o(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new bo(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Mo(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new yo(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Bo(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Po(this._scene)),this._shadowRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Qo(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new To(this._scene)),this._snapInitRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Vo={};var jo=65536,Go=5e6,zo=function(){function e(){w(this,e)}return C(e,[{key:"doublePrecisionEnabled",get:function(){return $.getDoublePrecisionEnabled()},set:function(e){$.setDoublePrecisionEnabled(e)}},{key:"maxDataTextureHeight",get:function(){return jo},set:function(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),jo=e}},{key:"maxGeometryBatchSize",get:function(){return Go},set:function(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Go=e}}]),e}(),Ko=new zo,Wo=C((function e(){w(this,e),this.maxVerts=Ko.maxGeometryBatchSize,this.maxIndices=3*Ko.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]})),Xo=$.mat4(),Jo=$.mat4();function Yo(e,t,i){for(var s=e.length,r=new Uint16Array(s),n=t[0],o=t[1],a=t[2],l=t[3]-n,u=t[4]-o,A=t[5]-a,c=65525,h=c/l,d=c/u,p=c/A,f=function(e){return e>=0?e:0},v=0;v=0?1:-1),o=(1-Math.abs(s))*(r>=0?1:-1),s=n,r=o}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function $o(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}var ea=$.mat4(),ta=$.mat4(),ia=$.vec4([0,0,0,1]),sa=$.vec3(),ra=$.vec3(),na=$.vec3(),oa=$.vec3(),aa=$.vec3(),la=$.vec3(),ua=$.vec3(),Aa=function(){function e(t){var i,s,r;w(this,e),console.info("Creating VBOBatchingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesBatchingLayer"+(t.solid?"-solid":"-surface")+(t.autoNormals?"-autonormals":"-normals")+(t.textureSet&&t.textureSet.colorTexture?"-colorTexture":"")+(t.textureSet&&t.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Vo[s])||(r=new Ho(i),Vo[s]=r,r._compile(),r.eagerCreateRenders(),i.on("compile",(function(){r._compile(),r.eagerCreateRenders()})),i.on("destroyed",(function(){delete Vo[s],r._destroy()}))),r),this._buffer=new Wo(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new Jt({origin:$.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:t.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)),t.uvDecodeMatrix?(this._state.uvDecodeMatrix=$.mat3(t.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,t.origin&&this._state.origin.set(t.origin),this.solid=!!t.solid}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)for(var C=0,M=o.length;C0){var F=ea;g?$.inverseMat4($.transposeMat4(g,ta),F):$.identityMat4(F,F),function(e,t,i,s,r){function n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}var o,a,l,u,A,c=new Float32Array([0,0,0,0]),h=new Float32Array([0,0,0,0]);for(A=0;Au&&(a=o,u=l),(l=n(h,$o(o=qo(h,"floor","ceil"))))>u&&(a=o,u=l),(l=n(h,$o(o=qo(h,"ceil","ceil"))))>u&&(a=o,u=l),s[r+A+0]=a[0],s[r+A+1]=a[1],s[r+A+2]=0}(F,n,n.length,y.normals,y.normals.length)}if(u)for(var E=0,k=u.length;E0)for(var H=0,V=a.length;H0)for(var j=0,G=l.length;j0){var s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Yo(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=$.mat4());if(e.positionsBuf=new Et(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(var r=0,n=this._portions.length;r0){var u=new Int8Array(i.normals);e.normalsBuf=new Et(t,t.ARRAY_BUFFER,u,i.normals.length,3,t.STATIC_DRAW,!0)}if(i.colors.length>0){var A=new Uint8Array(i.colors);e.colorsBuf=new Et(t,t.ARRAY_BUFFER,A,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.uv.length>0)if(e.uvDecodeMatrix){e.uvBuf=new Et(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,!1)}else{var c=Fi.getUVBounds(i.uv),h=Fi.compressUVs(i.uv,c.min,c.max),d=h.quantized;e.uvDecodeMatrix=$.mat3(h.decodeMatrix),e.uvBuf=new Et(t,t.ARRAY_BUFFER,d,d.length,2,t.STATIC_DRAW,!1)}if(i.metallicRoughness.length>0){var p=new Uint8Array(i.metallicRoughness);e.metallicRoughnessBuf=new Et(t,t.ARRAY_BUFFER,p,i.metallicRoughness.length,2,t.STATIC_DRAW,!1)}if(i.positions.length>0){var f=i.positions.length/3,v=new Float32Array(f);e.flagsBuf=new Et(t,t.ARRAY_BUFFER,v,v.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var g=new Uint8Array(i.pickColors);e.pickColorsBuf=new Et(t,t.ARRAY_BUFFER,g,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var m=new Float32Array(i.offsets);e.offsetsBuf=new Et(t,t.ARRAY_BUFFER,m,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var _=new Uint32Array(i.indices);e.indicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,_,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){var y=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,y,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}}},{key:"isEmpty",value:function(){return!this._state.indicesBuf}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=e,s=this._portions[i],r=4*s.vertsBaseIndex,n=4*s.numVerts,o=this._scratchMemory.getUInt8Array(n),a=t[0],l=t[1],u=t[2],A=t[3],c=0;c3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=e,a=this._portions[o],l=a.vertsBaseIndex,u=a.numVerts,A=l,c=u,h=!!(t&Ne),d=!!(t&Ge),p=!!(t&ze),f=!!(t&Ke),v=!!(t&We),g=!!(t&He),m=!!(t&Qe);r=!h||m||d||p&&!this.model.scene.highlightMaterial.glowThrough||f&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!h||m?so.NOT_RENDERED:f?so.SILHOUETTE_SELECTED:p?so.SILHOUETTE_HIGHLIGHTED:d?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var _=0;_=!h||m?so.NOT_RENDERED:f?so.EDGES_SELECTED:p?so.EDGES_HIGHLIGHTED:d?so.EDGES_XRAYED:v?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED;var y=h&&!m&&g?so.PICK:so.NOT_RENDERED,b=t&Ve?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var B=A,x=A+c;Bg)&&(g=w,s.set(m),r&&$.triangleNormal(d,p,f,r),v=!0)}}return v&&r&&($.transformVec3(this.model.worldNormalMatrix,r,r),$.normalizeVec3(r)),v}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}]),e}(),ca=function(e){g(i,Ao);var t=_(i);function i(e,s){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.edges,o=void 0!==n&&n;return w(this,i),t.call(this,e,s,{instancing:!0,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}]),i}(),ha=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t,i,s=this._scene,r=s._sectionPlanesState,n=s._lightsState,o=r.getNumAllocatedSectionPlanes()>0,a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),s.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),s.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),e=0,t=n.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),o&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),s.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),e=0,t=n.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}}]),i}(),da=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=i._lightsState,n=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry flat-shading drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),i.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=s.getNumAllocatedSectionPlanes();a> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var A=0,c=s.getNumAllocatedSectionPlanes();A 0.0) { "),o.push(" discard;"),o.push(" }"),o.push("}")}for(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=r.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),fa=function(e){g(i,ca);var t=_(i);function i(e,s){return w(this,i),t.call(this,e,s,{instancing:!0,edges:!0})}return C(i)}(),va=function(e){g(i,fa);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),ga=function(e){g(i,fa);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),ma=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}]),i}(),_a=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),ya=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),ba=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),Ba=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}]),i}(),xa=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),wa=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Pa={3e3:"linearToLinear",3001:"sRGBToLinear"},Ca=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Instancing geometry quality drawing vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("in vec4 modelNormalMatrixCol0;"),n.push("in vec4 modelNormalMatrixCol1;"),n.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.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);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),r&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),n.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Instancing geometry quality drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=s.lights.length;a0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),o.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),o.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),o.push(" return normalize(surf_norm );"),o.push(" }"),o.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),o.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),o.push(" vec2 st0 = dFdx( uv.st );"),o.push(" vec2 st1 = dFdy( uv.st );"),o.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),o.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),o.push(" vec3 N = normalize( surf_norm );"),o.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),o.push(" mat3 tsn = mat3( S, T, N );"),o.push(" return normalize( tsn * mapN );"),o.push("}"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),s.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Pa[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Pa[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=s.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Fa=function(e){g(i,ca);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i.gammaOutput,r=i._sectionPlanesState,n=i._lightsState,o=r.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),s&&(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("}")),o){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(var l=0,u=r.getNumAllocatedSectionPlanes();l> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(var c=0,h=r.getNumAllocatedSectionPlanes();c 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=n.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ra=$.vec3(),La=$.vec3(),Ua=$.vec3(),Oa=$.vec3(),Na=$.mat4(),Qa=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Ra;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=La;if(l){var m=$.transformPoint3(A,l,Ua);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,Na),(f=Oa)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ha=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new pa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ma(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new _a(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Ta(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Qa(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new ha(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new ha(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new da(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new da(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new Ca(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Ca(this._scene,!0)),this._pbrRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Fa(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Fa(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pa(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Ba(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new xa(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new va(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ga(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ma(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ya(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ma(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new _a(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new ba(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new wa(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Ta(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Qa(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Va={};var ja=new Uint8Array(4),Ga=new Float32Array(1),za=$.vec4([0,0,0,1]),Ka=new Float32Array(3),Wa=$.vec3(),Xa=$.vec3(),Ja=$.vec3(),Ya=$.vec3(),Za=$.vec3(),qa=$.vec3(),$a=$.vec3(),el=new Float32Array(4),tl=function(){function e(t){var i,s,r;w(this,e),console.info("Creating VBOInstancingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesInstancingLayer"+(t.solid?"-solid":"-surface")+(t.normals?"-normals":"-autoNormals"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Va[s])||(r=new Ha(i),Va[s]=r,r._compile(),r.eagerCreateRenders(),i.on("compile",(function(){r._compile(),r.eagerCreateRenders()})),i.on("destroyed",(function(){delete Va[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new Jt({numInstances:0,obb:$.OBB3(),origin:$.vec3(),geometry:t.geometry,textureSet:t.textureSet,pbrSupported:!1,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&this._state.origin.set(t.origin),this._finalized=!1,this.solid=!!t.solid,this.numIndices=t.geometry.numIndices}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){e.colorsBuf=new Et(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,!1),this._colors=[]}if(this._metallicRoughness.length>0){var o=new Uint8Array(this._metallicRoughness);e.metallicRoughnessBuf=new Et(s,s.ARRAY_BUFFER,o,this._metallicRoughness.length,2,s.STATIC_DRAW,!1)}if(n>0){e.flagsBuf=new Et(s,s.ARRAY_BUFFER,new Float32Array(n),n,1,s.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){e.offsetsBuf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,!1),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){e.positionsBuf=new Et(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,!1),e.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){var a=new Uint8Array(t.colorsCompressed);e.colorsBuf=new Et(s,s.ARRAY_BUFFER,a,a.length,4,s.STATIC_DRAW,!1)}if(t.uvCompressed&&t.uvCompressed.length>0){var l=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Et(s,s.ARRAY_BUFFER,l,l.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Et(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Et(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){var u=!1;e.modelMatrixCol0Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,u),e.modelMatrixCol1Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,u),e.modelMatrixCol2Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,u),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,u),e.modelNormalMatrixCol1Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,u),e.modelNormalMatrixCol2Buf=new Et(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,u),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){e.pickColorsBuf=new Et(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,!1),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";ja[0]=t[0],ja[1]=t[1],ja[2]=t[2],ja[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(ja,4*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Ne),r=!!(t&Ge),n=!!(t&ze),o=!!(t&Ke),a=!!(t&We),l=!!(t&He),u=!!(t&Qe),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,A|=(!s||u?so.NOT_RENDERED:o?so.SILHOUETTE_SELECTED:n?so.SILHOUETTE_HIGHLIGHTED:r?so.SILHOUETTE_XRAYED:so.NOT_RENDERED)<<4,A|=(!s||u?so.NOT_RENDERED:o?so.EDGES_SELECTED:n?so.EDGES_HIGHLIGHTED:r?so.EDGES_XRAYED:a?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED)<<8,A|=(s&&!u&&l?so.PICK:so.NOT_RENDERED)<<12,A|=(t&Ve?1:0)<<16,Ga[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(Ga,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ka[0]=t[0],Ka[1]=t[1],Ka[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Ka,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"getEachVertex",value:function(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;var i=this._state,s=i.geometry,r=this._portions[e];if(r)for(var n=s.quantizedPositions,o=i.origin,a=r.offset,l=o[0]+a[0],u=o[1]+a[1],A=o[2]+a[2],c=za,h=r.matrix,d=this.model.sceneModelMatrix,p=i.positionsDecodeMatrix,f=0,v=n.length;fm)&&(m=C,s.set(_),r&&$.triangleNormal(p,f,v,r),g=!0)}}return g&&r&&($.transformVec3(a.normalMatrix,r,r),$.transformVec3(this.model.worldNormalMatrix,r,r),$.normalizeVec3(r)),g}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}]),e}(),il=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}]),i}(),sl=function(e){g(i,il);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),rl=function(e){g(i,il);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),nl=$.vec3(),ol=$.vec3(),al=$.vec3(),ll=$.vec3(),ul=$.mat4(),Al=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=nl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=ol;if(l){var m=al;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,ul),(f=ll)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),cl=$.vec3(),hl=$.vec3(),dl=$.vec3(),pl=$.vec3(),fl=$.mat4(),vl=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=cl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=hl;if(l){var m=dl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,fl),(f=pl)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),gl=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new sl(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new rl(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Al(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new vl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),ml={};var _l=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;w(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]})),yl=function(){function e(t){var i,s,r;w(this,e),console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=ml[s])||(r=new gl(i),ml[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete ml[s],r._destroy()}))),r),this.model=t.model,this._buffer=new _l(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new Jt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var s=new Uint16Array(i.positions);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{var r=Yo(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Et(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.colors.length>0){var o=i.colors.length/4,a=new Float32Array(o);e.flagsBuf=new Et(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var l=new Float32Array(i.offsets);e.offsetsBuf=new Et(t,t.ARRAY_BUFFER,l,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var u=new Uint32Array(i.indices);e.indicesBuf=new Et(t,t.ELEMENT_ARRAY_BUFFER,u,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(r),o=t[0],a=t[1],l=t[2],u=t[3],A=0;A3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=2*e,a=this._portions[o],l=this._portions[o+1],u=a,A=l,c=!!(t&Ne),h=!!(t&Ge),d=!!(t&ze),p=!!(t&Ke),f=!!(t&He),v=!!(t&Qe);r=!c||v||h||d&&!this.model.scene.highlightMaterial.glowThrough||p&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!c||v?so.NOT_RENDERED:p?so.SILHOUETTE_SELECTED:d?so.SILHOUETTE_HIGHLIGHTED:h?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var g=c&&!v&&f?so.PICK:so.NOT_RENDERED,m=t&Ve?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var _=u,y=u+A;_0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):n.push(" outColor = vColor;"),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),xl=function(e){g(i,bl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),wl=$.vec3(),Pl=$.vec3(),Cl=$.vec3();$.vec3();var Ml=$.mat4(),Fl=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.canvas.gl,o=r.camera,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=wl;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Pl;if(l){var g=$.transformPoint3(A,l,Cl);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,Ml),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),El=$.vec3(),kl=$.vec3(),Il=$.vec3();$.vec3();var Dl=$.mat4(),Sl=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=El;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=kl;if(l){var g=$.transformPoint3(A,l,Il);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,Dl),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Tl=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._snapInitRenderer||(this._snapInitRenderer=new Fl(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Sl(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Bl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xl(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Fl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Sl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Rl={};var Ll=new Uint8Array(4),Ul=new Float32Array(1),Ol=new Float32Array(3),Nl=new Float32Array(4),Ql=function(){function e(t){var i,s,r;w(this,e),console.info("VBOInstancingLinesLayer"),this.model=t.model,this.material=t.material,this.sortId="LinesInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Rl[s])||(r=new Tl(i),Rl[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete Rl[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new Jt({obb:$.OBB3(),numInstances:0,origin:null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&(this._state.origin=$.vec3(t.origin)),this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){this._state.colorsBuf=new Et(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,!1),this._colors=[]}if(r>0){this._state.flagsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){this._state.offsetsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){var n=new Uint8Array(i.colorsCompressed);t.colorsBuf=new Et(e,e.ARRAY_BUFFER,n,n.length,4,e.STATIC_DRAW,!1)}if(i.positionsCompressed&&i.positionsCompressed.length>0){t.positionsBuf=new Et(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,!1),t.positionsDecodeMatrix=$.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Et(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){var o=!1;this._state.modelMatrixCol0Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol1Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol2Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,o),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Ll[0]=t[0],Ll[1]=t[1],Ll[2]=t[2],Ll[3]=t[3],this._state.colorsBuf.setData(Ll,4*e,4)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Ne),r=!!(t&Ge),n=!!(t&ze),o=!!(t&Ke),a=!!(t&We),l=!!(t&He),u=!!(t&Qe),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,A|=(!s||u?so.NOT_RENDERED:o?so.SILHOUETTE_SELECTED:n?so.SILHOUETTE_HIGHLIGHTED:r?so.SILHOUETTE_XRAYED:so.NOT_RENDERED)<<4,A|=(!s||u?so.NOT_RENDERED:o?so.EDGES_SELECTED:n?so.EDGES_HIGHLIGHTED:r?so.EDGES_XRAYED:a?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED)<<8,A|=(s&&!u&&l?so.PICK:so.NOT_RENDERED)<<12,A|=(t&Ve?255:0)<<16,Ul[0]=A,this._state.flagsBuf.setData(Ul,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ol[0]=t[0],Ol[1]=t[1],Ol[2]=t[2],this._state.offsetsBuf.setData(Ol,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Nl[0]=t[0],Nl[1]=t[4],Nl[2]=t[8],Nl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Nl,i),Nl[0]=t[1],Nl[1]=t[5],Nl[2]=t[9],Nl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Nl,i),Nl[0]=t[2],Nl[1]=t[6],Nl[2]=t[10],Nl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Nl,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,so.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,so.PICK)}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}]),e}(),Hl=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}]),i}(),Vl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),jl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),r){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}]),i}(),Gl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}]),i}(),zl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),Kl=function(e){g(i,Hl);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}]),i}(),Wl=$.vec3(),Xl=$.vec3(),Jl=$.vec3(),Yl=$.vec3(),Zl=$.mat4(),ql=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Wl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Xl;if(l){var m=Jl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,Zl),(f=Yl)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),$l=$.vec3(),eu=$.vec3(),tu=$.vec3(),iu=$.vec3(),su=$.mat4(),ru=function(e){g(i,Ao);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=$l;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=eu;if(l){var m=tu;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Te(d,g,su),(f=iu)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),nu=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Vl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new jl(this._scene)),this._silhouetteRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Gl(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new zl(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Kl(this._scene)),this._occlusionRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new ql(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new ru(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),ou={};var au=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;w(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]})),lu=function(){function e(t){w(this,e),console.info("Creating VBOBatchingPointsLayer"),this.model=t.model,this.sortId="PointsBatchingLayer",this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=ou[t];return i||(i=new nu(e),ou[t]=i,i._compile(),e.on("compile",(function(){i._compile()})),e.on("destroyed",(function(){delete ou[t],i._destroy()}))),i}(t.model.scene),this._buffer=new au(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new Jt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var s=new Uint16Array(i.positions);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{var r=Yo(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Et(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Et(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.STATIC_DRAW,!1)}if(i.positions.length>0){var o=i.positions.length/3,a=new Float32Array(o);e.flagsBuf=new Et(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var l=new Uint8Array(i.pickColors);e.pickColorsBuf=new Et(t,t.ARRAY_BUFFER,l,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var u=new Float32Array(i.offsets);e.offsetsBuf=new Et(t,t.ARRAY_BUFFER,u,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized"}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(r),o=t[0],a=t[1],l=t[2],u=0;u0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),cu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(B(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),hu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}]),i}(),du=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),pu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),fu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),r){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return n.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),vu=function(e){g(i,uu);var t=_(i);function i(){return w(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),gu=$.vec3(),mu=$.vec3(),_u=$.vec3();$.vec3();var yu=$.mat4(),bu=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.canvas.gl,o=r.camera,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=gu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=mu;if(l){var g=$.transformPoint3(A,l,_u);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,yu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Bu=$.vec3(),xu=$.vec3(),wu=$.vec3();$.vec3();var Pu=$.mat4(),Cu=function(e){g(i,Ao);var t=_(i);function i(e){return w(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=Bu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=xu;if(l){var g=$.transformPoint3(A,l,wu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Te(d,v,Pu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(B(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Mu=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Au(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new cu(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new fu(this._scene)),this._depthRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new hu(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new du(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new pu(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new vu(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new bu(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Cu(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Fu={};var Eu=new Uint8Array(4),ku=new Float32Array(1),Iu=new Float32Array(3),Du=new Float32Array(4),Su=function(){function e(t){var i,s,r;w(this,e),console.info("VBOInstancingPointsLayer"),this.model=t.model,this.material=t.material,this.sortId="PointsInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Fu[s])||(r=new Mu(i),Fu[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete Fu[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new Jt({obb:$.OBB3(),numInstances:0,origin:t.origin?$.vec3(t.origin):null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){i.flagsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){i.offsetsBuf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){i.positionsBuf=new Et(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,!1),i.positionsDecodeMatrix=$.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){var r=new Uint8Array(s.colorsCompressed);i.colorsBuf=new Et(e,e.ARRAY_BUFFER,r,r.length,4,e.STATIC_DRAW,!1)}if(this._modelMatrixCol0.length>0){var n=!1;i.modelMatrixCol0Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,n),i.modelMatrixCol1Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,n),i.modelMatrixCol2Buf=new Et(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,n),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){i.pickColorsBuf=new Et(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,!1),this._pickColors=[]}i.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Eu[0]=t[0],Eu[1]=t[1],Eu[2]=t[2],this._state.colorsBuf.setData(Eu,3*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Ne),r=!!(t&Ge),n=!!(t&ze),o=!!(t&Ke),a=!!(t&We),l=!!(t&He),u=!!(t&Qe),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,A|=(!s||u?so.NOT_RENDERED:o?so.SILHOUETTE_SELECTED:n?so.SILHOUETTE_HIGHLIGHTED:r?so.SILHOUETTE_XRAYED:so.NOT_RENDERED)<<4,A|=(!s||u?so.NOT_RENDERED:o?so.EDGES_SELECTED:n?so.EDGES_HIGHLIGHTED:r?so.EDGES_XRAYED:a?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED)<<8,A|=(s&&!u&&l?so.PICK:so.NOT_RENDERED)<<12,A|=(t&Ve?255:0)<<16,ku[0]=A,this._state.flagsBuf.setData(ku,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Iu[0]=t[0],Iu[1]=t[1],Iu[2]=t[2],this._state.offsetsBuf.setData(Iu,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Du[0]=t[0],Du[1]=t[4],Du[2]=t[8],Du[3]=t[12],this._state.modelMatrixCol0Buf.setData(Du,i),Du[0]=t[1],Du[1]=t[5],Du[2]=t[9],Du[3]=t[13],this._state.modelMatrixCol1Buf.setData(Du,i),Du[0]=t[2],Du[1]=t[6],Du[2]=t[10],Du[3]=t[14],this._state.modelMatrixCol2Buf.setData(Du,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,so.PICK)}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,so.PICK)}},{key:"drawPickNormals",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,so.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,so.PICK)}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}]),e}(),Tu=$.vec3(),Ru=$.vec3(),Lu=$.mat4(),Uu=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=r.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=Tu;if(f){var m=$.transformPoint3(c,u,Ru);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Te(d,g,Lu)}else p=d;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),o.drawArrays(o.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),o.drawArrays(o.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),o.drawArrays(o.LINES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Ou=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}},{key:"eagerCreateRenders",value:function(){}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Uu(this._scene,!1)),this._colorRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy()}}]),e}(),Nu={};var Qu=C((function e(){w(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]})),Hu=function(){function e(){w(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}},{key:"bindLineIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}]),e}(),Vu=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;w(this,e),this._gl=t,this._texture=i,this._textureWidth=s,this._textureHeight=r,this._textureData=n}return C(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),ju={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(ju,null,4));var e=0;Object.keys(ju).forEach((function(t){t.startsWith("size")&&(e+=ju[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/ju.totalLines).toFixed(2)));var t={};Object.keys(ju).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((ju[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var Gu=function(){function e(){w(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,s,r){var n=t.length;this.numPortions=n;var o=4096,a=Math.ceil(n/512);if(0===a)throw"texture height===0";var l=new Uint8Array(16384*a);ju.sizeDataColorsAndFlags+=l.byteLength,ju.numberOfTextures++;for(var u=0;u>24&255,s[u]>>16&255,s[u]>>8&255,255&s[u]],32*u+16),l.set([r[u]>>24&255,r[u]>>16&255,r[u]>>8&255,255&r[u]],32*u+20);var A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,A,o,a,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";var r=new Float32Array(1536*s).fill(0);ju.sizeDataTextureOffsets+=r.byteLength,ju.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,n,i,s,r)}},{key:"generateTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var s=2048,r=Math.ceil(i/512),n=new Float32Array(8192*r);ju.numberOfTextures++;for(var o=0;o65536&&ju.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[s]){var r=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/2})),(this._state.numVertices+n>4096*Ku||r+o>4096*Ku)&&ju.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*Ku&&r+o<=4096*Ku)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var s=[];t.buckets.forEach((function(e,r){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(r):"".concat(t.id,"#").concat(r),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);s.push(a)}));var r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/2/8)*2;ju.overheadSizeAlignementIndices+=2*(i-t.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(t.indices),t.indices=s}var r=t.positionsCompressed,n=t.indices,o=this._buffer;o.positionsCompressed.push(r);var a,l=o.lenPositionsCompressed/3,u=r.length/3;o.lenPositionsCompressed+=r.length;var A,c=0;n&&(c=n.length/2,u<=256?(A=o.indices8Bits,a=o.lenIndices8Bits/2,o.lenIndices8Bits+=n.length):u<=65536?(A=o.indices16Bits,a=o.lenIndices16Bits/2,o.lenIndices16Bits+=n.length):(A=o.indices32Bits,a=o.lenIndices32Bits/2,o.lenIndices32Bits+=n.length),A.push(n));return this._state.numVertices+=u,ju.numberOfGeometries++,{vertexBase:l,numVertices:u,numLines:c,indicesBase:a}}},{key:"_createSubPortion",value:function(e,t){var i,s=e.color,r=e.colors,n=e.opacity,o=e.meshMatrix,a=e.pickColor,l=this._buffer,u=this._state;l.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),l.perObjectInstancePositioningMatrices.push(o||Zu),l.perObjectSolid.push(!!e.solid),r?l.perObjectColors.push([255*r[0],255*r[1],255*r[2],255]):s&&l.perObjectColors.push([s[0],s[1],s[2],n]),l.perObjectPickColors.push(a),l.perObjectVertexBases.push(t.vertexBase),i=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,l.perObjectIndexBaseOffsets.push(i/2-t.indicesBase);var A=this._subPortions.length;if(t.numLines>0){var c,h=2*t.numLines;t.numVertices<=256?(c=l.perLineNumberPortionId8Bits,u.numIndices8Bits+=h,ju.totalLines8Bits+=t.numLines):t.numVertices<=65536?(c=l.perLineNumberPortionId16Bits,u.numIndices16Bits+=h,ju.totalLines16Bits+=t.numLines):(c=l.perLineNumberPortionId32Bits,u.numIndices32Bits+=h,ju.totalLines32Bits+=t.numLines),ju.totalLines+=t.numLines;for(var d=0;d0&&(i.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,r.indices8Bits,r.lenIndices8Bits)),r.lenIndices16Bits>0&&(i.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,r.indices16Bits,r.lenIndices16Bits)),r.lenIndices32Bits>0&&(i.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,r.indices32Bits,r.lenIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Xu))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=this._portionToSubPortionsMap[e],n=0,o=r.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=!!(t&Ne),a=!!(t&Ge),l=!!(t&ze),u=!!(t&Ke),A=!!(t&He),c=!!(t&Qe);r=!o||c||a?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!o||c?so.NOT_RENDERED:u?so.SILHOUETTE_SELECTED:l?so.SILHOUETTE_HIGHLIGHTED:a?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var h=o&&!c&&A?so.PICK:so.NOT_RENDERED,d=this._dataTextureState,p=this.model.scene.canvas.gl;Xu[0]=r,Xu[1]=n,Xu[3]=h,d.texturePerObjectColorsAndFlags._textureData.set(Xu,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,Xu))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=this._portionToSubPortionsMap[e],r=0,n=s.length;r2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var s=t&Ve?255:0,r=this._dataTextureState,n=this.model.scene.canvas.gl;Xu[0]=s,Xu[1]=0,Xu[2]=1,Xu[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(Xu,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,Xu))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Ju))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Wu))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){}},{key:"drawSilhouetteHighlighted",value:function(e,t){}},{key:"drawSilhouetteSelected",value:function(e,t){}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){}},{key:"drawSnap",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),$u=$.vec3(),eA=$.vec3(),tA=$.vec3();$.vec3();var iA=$.vec4(),sA=$.mat4(),rA=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=$u;if(f){var m=$.transformPoint3(c,u,eA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Te(r.viewMatrix,g,sA),(p=tA)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Ft(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n0,n=[];n.push("#version 300 es"),n.push("// TrianglesDataTextureColorRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=s.lights.length;l0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),nA=new Float32Array([1,1,1]),oA=$.vec3(),aA=$.vec3(),lA=$.vec3();$.vec3();var uA=$.mat4(),AA=function(){function e(t,i){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=r.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=oA;if(u){var g=aA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Te(d,v,uA),(f=lA)[0]=r.eye[0]-v[0],f[1]=r.eye[1]-v[1],f[2]=r.eye[2]-v[2]}else p=d,f=r.eye;if(o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===so.SILHOUETTE_XRAYED){var m=s.xrayMaterial._state,_=m.fillColor,y=m.fillAlpha;o.uniform4f(this._uColor,_[0],_[1],_[2],y)}else if(i===so.SILHOUETTE_HIGHLIGHTED){var b=s.highlightMaterial._state,B=b.fillColor,x=b.fillAlpha;o.uniform4f(this._uColor,B[0],B[1],B[2],x)}else if(i===so.SILHOUETTE_SELECTED){var w=s.selectedMaterial._state,P=w.fillColor,C=w.fillAlpha;o.uniform4f(this._uColor,P[0],P[1],P[2],C)}else o.uniform4fv(this._uColor,nA);if(s.logarithmicDepthBufferEnabled){var M=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,M)}var F=s._sectionPlanesState.getNumAllocatedSectionPlanes(),E=s._sectionPlanesState.sectionPlanes.length;if(F>0)for(var k=s._sectionPlanesState.sectionPlanes,I=t.layerIndex*E,D=n.renderFlags,S=0;S0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),cA=new Float32Array([0,0,0,1]),hA=$.vec3(),dA=$.vec3();$.vec3();var pA=$.mat4(),fA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=hA;if(f){var m=$.transformPoint3(c,u,dA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Te(d,g,pA)}else p=d;if(o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),i===so.EDGES_XRAYED){var _=r.xrayMaterial._state,y=_.edgeColor,b=_.edgeAlpha;o.uniform4f(this._uColor,y[0],y[1],y[2],b)}else if(i===so.EDGES_HIGHLIGHTED){var B=r.highlightMaterial._state,x=B.edgeColor,w=B.edgeAlpha;o.uniform4f(this._uColor,x[0],x[1],x[2],w)}else if(i===so.EDGES_SELECTED){var P=r.selectedMaterial._state,C=P.edgeColor,M=P.edgeAlpha;o.uniform4f(this._uColor,C[0],C[1],C[2],M)}else o.uniform4fv(this._uColor,cA);var F=r._sectionPlanesState.getNumAllocatedSectionPlanes(),E=r._sectionPlanesState.sectionPlanes.length;if(F>0)for(var k=r._sectionPlanesState.sectionPlanes,I=t.layerIndex*E,D=s.renderFlags,S=0;S0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),vA=$.vec3(),gA=$.vec3(),mA=$.mat4(),_A=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=vA;if(f){var m=$.transformPoint3(c,u,gA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Te(d,g,mA)}else p=d;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*y,x=s.renderFlags,w=0;w<_;w++){var P=this._uSectionPlanes[w];if(P)if(w0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),yA=$.vec3(),bA=$.vec3(),BA=$.vec3(),xA=$.mat4(),wA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate;A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==c[0]||0!==c[1]||0!==c[2],v=0!==h[0]||0!==h[1]||0!==h[2];if(f||v){var g=yA;if(f){var m=$.transformPoint3(d,c,bA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=h[0],g[1]+=h[1],g[2]+=h[2],s=Te(a.viewMatrix,g,xA),(r=BA)[0]=a.eye[0]-g[0],r[1]=a.eye[1]-g[1],r[2]=a.eye[2]-g[2]}else s=a.viewMatrix,r=a.eye;if(l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),l.uniform3fv(this._uCameraEyeRtc,r),l.uniform1i(this._uRenderPass,i),o.logarithmicDepthBufferEnabled){var _=2/(Math.log(a.project.far+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,_)}var y=o._sectionPlanesState.getNumAllocatedSectionPlanes(),b=o._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=o._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),PA=$.vec3(),CA=$.vec3(),MA=$.vec3();$.vec3();var FA=$.mat4(),EA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=e.pickViewMatrix||a.viewMatrix;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==h[0]||0!==h[1]||0!==h[2]){var v=PA;if(c){var g=CA;$.transformPoint3(d,c,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=h[0],v[1]+=h[1],v[2]+=h[2],s=Te(f,v,FA),(r=MA)[0]=a.eye[0]-v[0],r[1]=a.eye[1]-v[1],r[2]=a.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else s=f,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(l.uniform3fv(this._uCameraEyeRtc,r),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniform1f(this._uPickZNear,e.pickZNear),l.uniform1f(this._uPickZFar,e.pickZFar),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),o.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,m)}var _=o._sectionPlanesState.getNumAllocatedSectionPlanes(),y=o._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=o._sectionPlanesState.sectionPlanes,B=t.layerIndex*y,x=n.renderFlags,w=0;w<_;w++){var P=this._uSectionPlanes[w];if(P)if(w0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),kA=$.vec3(),IA=$.vec3(),DA=$.vec3(),SA=$.vec3();$.vec3();var TA=$.mat4(),RA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=kA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=IA;if(m){var b=$.transformPoint3(d,c,DA);y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],s=Te(v,y,TA),(r=SA)[0]=a.eye[0]-y[0],r[1]=a.eye[1]-y[1],r[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else s=v,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,r),l.uniform2fv(this.uVectorA,e.snapVectorA),l.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var B=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,B);var x=o._sectionPlanesState.getNumAllocatedSectionPlanes(),w=o._sectionPlanesState.sectionPlanes.length;if(x>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*w,M=n.renderFlags,F=0;F0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),l.drawArrays(S,0,u.numEdgeIndices8Bits)),u.numEdgeIndices16Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),l.drawArrays(S,0,u.numEdgeIndices16Bits)),u.numEdgeIndices32Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),l.drawArrays(S,0,u.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),LA=$.vec3(),UA=$.vec3(),OA=$.vec3(),NA=$.vec3();$.vec3();var QA=$.mat4(),HA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=LA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=UA;if(m){var b=OA;$.transformPoint3(d,c,b),y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],s=Te(v,y,QA),(r=NA)[0]=a.eye[0]-y[0],r[1]=a.eye[1]-y[1],r[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else s=v,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,r),l.uniform2fv(this._uVectorA,e.snapVectorA),l.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var B=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,B);var x=o._sectionPlanesState.getNumAllocatedSectionPlanes(),w=o._sectionPlanesState.sectionPlanes.length;if(x>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*w,M=n.renderFlags,F=0;F0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),VA=$.vec3(),jA=$.vec3(),GA=$.vec3();$.vec3();var zA=$.mat4(),KA=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=e.pickViewMatrix||n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=VA;if(u){var g=jA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Te(d,v,zA),(f=GA)[0]=n.eye[0]-v[0],f[1]=n.eye[1]-v[1],f[2]=n.eye[2]-v[2]}else p=d,f=n.eye;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0)for(var y=r._sectionPlanesState.sectionPlanes,b=t.layerIndex*_,B=s.renderFlags,x=0;x0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),WA=$.vec3(),XA=$.vec3(),JA=$.vec3();$.vec3();var YA=$.mat4(),ZA=function(){function e(t){w(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=WA;if(f){var m=$.transformPoint3(c,u,XA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Te(r.viewMatrix,g,YA),(p=JA)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),qA=$.vec3(),$A=$.vec3(),ec=$.vec3();$.vec3();var tc=$.mat4(),ic=function(){function e(t){w(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));var f=0!==l[0]||0!==l[1]||0!==l[2],v=0!==u[0]||0!==u[1]||0!==u[2];if(f||v){var g=qA;if(f){var m=$A;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],d=Te(h,g,tc),(p=ec)[0]=n.eye[0]-g[0],p[1]=n.eye[1]-g[1],p[2]=n.eye[2]-g[2]}else d=h,p=n.eye;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,c),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*y,x=s.renderFlags,w=0;w<_;w++){var P=this._uSectionPlanes[w];if(P)if(w0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&mt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),mt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(mt.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&mt.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&&mt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&mt.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}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),sc=$.vec3(),rc=$.vec3(),nc=$.vec3();$.vec3(),$.vec4();var oc=$.mat4(),ac=function(){function e(t,i){w(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=sc;if(f){var m=$.transformPoint3(c,u,rc);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Te(r.viewMatrix,g,oc),(p=nc)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniform2fv(this._uPickClipPos,e.pickClipPos),o.uniform2f(this._uDrawingBufferSize,o.drawingBufferWidth,o.drawingBufferHeight),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var B=s._sectionPlanesState.sectionPlanes,x=t.layerIndex*b,w=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new Ft(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),lc=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new AA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new EA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new ac(this._scene)),this._snapRenderer||(this._snapRenderer=new RA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new HA(this._scene)),this._snapRenderer||(this._snapRenderer=new RA(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new rA(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new rA(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new AA(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new ZA(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new ic(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new fA(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new _A(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wA(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ac(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new ac(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new EA(this._scene)),this._pickDepthRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new RA(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new HA(this._scene)),this._snapInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new KA(this._scene)),this._occlusionRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}]),e}(),uc={};var Ac=C((function e(){w(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),cc=function(){function e(){w(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}]),e}(),hc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(hc,null,4));var e=0;Object.keys(hc).forEach((function(t){t.startsWith("size")&&(e+=hc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/hc.totalPolygons).toFixed(2)));var t={};Object.keys(hc).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((hc[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var dc=function(){function e(){w(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"createTextureForColorsAndFlags",value:function(e,t,i,s,r,n,o){var a=t.length;this.numPortions=a;var l=4096,u=Math.ceil(a/512);if(0===u)throw"texture height===0";var A=new Uint8Array(16384*u);hc.sizeDataColorsAndFlags+=A.byteLength,hc.numberOfTextures++;for(var c=0;c>24&255,s[c]>>16&255,s[c]>>8&255,255&s[c]],32*c+16),A.set([r[c]>>24&255,r[c]>>16&255,r[c]>>8&255,255&r[c]],32*c+20),A.set([n[c]>>24&255,n[c]>>16&255,n[c]>>8&255,255&n[c]],32*c+24),A.set([o[c]?1:0,0,0,0],32*c+28);var h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,A,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,h,l,u,A)}},{key:"createTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";var r=new Float32Array(1536*s).fill(0);hc.sizeDataTextureOffsets+=r.byteLength,hc.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Vu(e,n,i,s,r)}},{key:"createTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var s=2048,r=Math.ceil(i/512),n=new Float32Array(8192*r);hc.numberOfTextures++;for(var o=0;o65536&&hc.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[s]){var r=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/3})),(this._state.numVertices+n>4096*fc||r+o>4096*fc)&&hc.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*fc&&r+o<=4096*fc)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var s=[];t.buckets.forEach((function(e,r){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(r):"".concat(t.id,"#").concat(r),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);s.push(a)}));var r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/3/8)*3;hc.overheadSizeAlignementIndices+=2*(i-t.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){var r=8*Math.ceil(t.edgeIndices.length/2/8)*2;hc.overheadSizeAlignementEdgeIndices+=2*(r-t.edgeIndices.length);var n=new Uint32Array(r);n.fill(0),n.set(t.edgeIndices),t.edgeIndices=n}var o=t.positionsCompressed,a=t.indices,l=t.edgeIndices,u=this._buffer;u.positionsCompressed.push(o);var A,c=u.lenPositionsCompressed/3,h=o.length/3;u.lenPositionsCompressed+=o.length;var d,p,f=0;a&&(f=a.length/3,h<=256?(d=u.indices8Bits,A=u.lenIndices8Bits/3,u.lenIndices8Bits+=a.length):h<=65536?(d=u.indices16Bits,A=u.lenIndices16Bits/3,u.lenIndices16Bits+=a.length):(d=u.indices32Bits,A=u.lenIndices32Bits/3,u.lenIndices32Bits+=a.length),d.push(a));var v,g=0;l&&(g=l.length/2,h<=256?(v=u.edgeIndices8Bits,p=u.lenEdgeIndices8Bits/2,u.lenEdgeIndices8Bits+=l.length):h<=65536?(v=u.edgeIndices16Bits,p=u.lenEdgeIndices16Bits/2,u.lenEdgeIndices16Bits+=l.length):(v=u.edgeIndices32Bits,p=u.lenEdgeIndices32Bits/2,u.lenEdgeIndices32Bits+=l.length),v.push(l));return this._state.numVertices+=h,hc.numberOfGeometries++,{vertexBase:c,numVertices:h,numTriangles:f,numEdges:g,indicesBase:A,edgeIndicesBase:p}}},{key:"_createSubPortion",value:function(e,t,i,s){var r=e.color;e.metallic,e.roughness;var n,o,a=e.colors,l=e.opacity,u=e.meshMatrix,A=e.pickColor,c=this._buffer,h=this._state;c.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),c.perObjectInstancePositioningMatrices.push(u||yc),c.perObjectSolid.push(!!e.solid),a?c.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):r&&c.perObjectColors.push([r[0],r[1],r[2],l]),c.perObjectPickColors.push(A),c.perObjectVertexBases.push(t.vertexBase),n=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,c.perObjectIndexBaseOffsets.push(n/3-t.indicesBase),o=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,c.perObjectEdgeIndexBaseOffsets.push(o/2-t.edgeIndicesBase);var d=this._subPortions.length;if(t.numTriangles>0){var p,f=3*t.numTriangles;t.numVertices<=256?(p=c.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=f,hc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(p=c.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=f,hc.totalPolygons16Bits+=t.numTriangles):(p=c.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=f,hc.totalPolygons32Bits+=t.numTriangles),hc.totalPolygons+=t.numTriangles;for(var v=0;v0){var g,m=2*t.numEdges;t.numVertices<=256?(g=c.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=m,hc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=c.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=m,hc.totalEdges16Bits+=t.numEdges):(g=c.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=m,hc.totalEdges32Bits+=t.numEdges),hc.totalEdges+=t.numEdges;for(var _=0;_0&&(i.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId8Bits)),r.perEdgeNumberPortionId16Bits.length>0&&(i.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId16Bits)),r.perEdgeNumberPortionId32Bits.length>0&&(i.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId32Bits)),r.lenIndices8Bits>0&&(i.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(s,r.indices8Bits,r.lenIndices8Bits)),r.lenIndices16Bits>0&&(i.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(s,r.indices16Bits,r.lenIndices16Bits)),r.lenIndices32Bits>0&&(i.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(s,r.indices32Bits,r.lenIndices32Bits)),r.lenEdgeIndices8Bits>0&&(i.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(s,r.edgeIndices8Bits,r.lenEdgeIndices8Bits)),r.lenEdgeIndices16Bits>0&&(i.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(s,r.edgeIndices16Bits,r.lenEdgeIndices16Bits)),r.lenEdgeIndices32Bits>0&&(i.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(s,r.edgeIndices32Bits,r.lenEdgeIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,i){t&Ne&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&ze&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ge&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Ve&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&We&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Qe&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ne?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ge?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&Ve?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,gc)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=this._portionToSubPortionsMap[e],n=0,o=r.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=!!(t&Ne),a=!!(t&Ge),l=!!(t&ze),u=!!(t&Ke),A=!!(t&We),c=!!(t&He),h=!!(t&Qe);r=!o||h||a?so.NOT_RENDERED:i?so.COLOR_TRANSPARENT:so.COLOR_OPAQUE,n=!o||h?so.NOT_RENDERED:u?so.SILHOUETTE_SELECTED:l?so.SILHOUETTE_HIGHLIGHTED:a?so.SILHOUETTE_XRAYED:so.NOT_RENDERED;var d=0;d=!o||h?so.NOT_RENDERED:u?so.EDGES_SELECTED:l?so.EDGES_HIGHLIGHTED:a?so.EDGES_XRAYED:A?i?so.EDGES_COLOR_TRANSPARENT:so.EDGES_COLOR_OPAQUE:so.NOT_RENDERED;var p=o&&!h&&c?so.PICK:so.NOT_RENDERED,f=this._dtxState,v=this.model.scene.canvas.gl;gc[0]=r,gc[1]=n,gc[2]=d,gc[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(gc,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),v.bindTexture(v.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),v.texSubImage2D(v.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,v.RGBA_INTEGER,v.UNSIGNED_BYTE,gc))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=this._portionToSubPortionsMap[e],r=0,n=s.length;r2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var s=t&Ve?255:0,r=this._dtxState,n=this.model.scene.canvas.gl;gc[0]=s,gc[1]=0,gc[2]=1,gc[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(gc,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,gc))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,mc))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,vc))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,so.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){var i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){var s=t.gl;i?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),t.backfaces=i}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,so.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,so.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,so.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,so.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,so.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,so.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,so.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,so.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,so.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,so.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,so.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,so.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,so.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),Bc=function(){function e(t){w(this,e),this.id=t.id,this.colorTexture=t.colorTexture,this.metallicRoughnessTexture=t.metallicRoughnessTexture,this.normalsTexture=t.normalsTexture,this.emissiveTexture=t.emissiveTexture,this.occlusionTexture=t.occlusionTexture}return C(e,[{key:"destroy",value:function(){}}]),e}(),xc=function(){function e(t){w(this,e),this.id=t.id,this.texture=t.texture}return C(e,[{key:"destroy",value:function(){this.texture&&(this.texture.destroy(),this.texture=null)}}]),e}(),wc={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}},Pc=function(){function e(t,i,s){w(this,e),this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=t,this.onProgress=i,this.onError=s}return C(e,[{key:"itemStart",value:function(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}},{key:"itemEnd",value:function(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}},{key:"itemError",value:function(e){void 0!==this.onError&&this.onError(e)}},{key:"resolveURL",value:function(e){return this.urlModifier?this.urlModifier(e):e}},{key:"setURLModifier",value:function(e){return this.urlModifier=e,this}},{key:"addHandler",value:function(e,t){return this.handlers.push(e,t),this}},{key:"removeHandler",value:function(e){var t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}},{key:"getHandler",value:function(e){for(var t=0,i=this.handlers.length;t0&&void 0!==arguments[0]?arguments[0]:4;w(this,e),this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}return C(e,[{key:"_initWorker",value:function(e){if(!this.workers[e]){var t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}},{key:"_getIdleWorker",value:function(){for(var e=0;e0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Ic++}return this._transcoderPending}},{key:"transcode",value:function(e,t){var i=this,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise((function(r,n){var o=s;i._init().then((function(){return i._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e)})).then((function(e){var i=e.data,s=i.mipmaps,o=(i.width,i.height,i.format),a=i.type,l=i.error,u=i.dfdTransferFn,A=i.dfdFlags;if("error"===a)return n(l);t.setCompressedData({mipmaps:s,props:{format:o,minFilter:1===s.length?1006:1008,magFilter:1===s.length?1006:1008,encoding:2===u?3001:3e3,premultiplyAlpha:!!(1&A)}}),r()}))}))}},{key:"destroy",value:function(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Ic--}}]),e}();Dc.BasisFormat={ETC1S:0,UASTC_4x4:1},Dc.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},Dc.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},Dc.BasisWorker=function(){var e,t,i,s=_EngineFormat,r=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",(function(o){var A,c=o.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((function(e){i={wasmBinary:A,onRuntimeInitialized:e},BASIS(i)})).then((function(){i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((function(){try{for(var t=function(t){var o=new i.KTX2File(new Uint8Array(t));function A(){o.close(),o.delete()}if(!o.isValid())throw A(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");var c=o.isUASTC()?n.UASTC_4x4:n.ETC1S,h=o.getWidth(),d=o.getHeight(),p=o.getLevels(),f=o.getHasAlpha(),v=o.getDFDTransferFunc(),g=o.getDFDFlags(),m=function(t,i,o,A){for(var c,h,d=t===n.ETC1S?a:l,p=0;p>t;i.sort(Qc);for(var a=new Int32Array(e.length),l=0,u=i.length;le[r+1]){var o=e[r];e[r]=e[r+1],e[r+1]=o}Vc=new Int32Array(e),t.sort(jc);for(var a=new Int32Array(e.length),l=0,u=t.length;l0)for(var s=i._meshes,r=0,n=s.length;r0)for(var o=this._meshes,a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._dtxEnabled=s.scene.dtxEnabled&&!1!==r.dtxEnabled,s._enableVertexWelding=!1,s._enableIndexBucketing=!1,s._vboBatchingLayerScratchMemory=io(),s._textureTranscoder=r.textureTranscoder||Tc(s.scene.viewer),s._maxGeometryBatchSize=r.maxGeometryBatchSize,s._aabb=$.collapseAABB3(),s._aabbDirty=!0,s._quantizationRanges={},s._vboInstancingLayers={},s._vboBatchingLayers={},s._dtxLayers={},s._meshList=[],s.layerList=[],s._entityList=[],s._geometries={},s._dtxBuckets={},s._textures={},s._textureSets={},s._transforms={},s._meshes={},s._unusedMeshes={},s._entities={},s.renderFlags=new jr,s.numGeometries=0,s.numPortions=0,s.numVisibleLayerPortions=0,s.numTransparentLayerPortions=0,s.numXRayedLayerPortions=0,s.numHighlightedLayerPortions=0,s.numSelectedLayerPortions=0,s.numEdgesLayerPortions=0,s.numPickableLayerPortions=0,s.numClippableLayerPortions=0,s.numCulledLayerPortions=0,s.numEntities=0,s._numTriangles=0,s._numLines=0,s._numPoints=0,s._edgeThreshold=r.edgeThreshold||10,s._origin=$.vec3(r.origin||[0,0,0]),s._position=$.vec3(r.position||[0,0,0]),s._rotation=$.vec3(r.rotation||[0,0,0]),s._quaternion=$.vec4(r.quaternion||[0,0,0,1]),s._conjugateQuaternion=$.vec4(r.quaternion||[0,0,0,1]),r.rotation&&$.eulerToQuaternion(s._rotation,"XYZ",s._quaternion),s._scale=$.vec3(r.scale||[1,1,1]),s._worldRotationMatrix=$.mat4(),s._worldRotationMatrixConjugate=$.mat4(),s._matrix=$.mat4(),s._matrixDirty=!0,s._rebuildMatrices(),s._worldNormalMatrix=$.mat4(),$.inverseMat4(s._matrix,s._worldNormalMatrix),$.transposeMat4(s._worldNormalMatrix),(r.matrix||r.position||r.rotation||r.scale||r.quaternion)&&(s._viewMatrix=$.mat4(),s._viewNormalMatrix=$.mat4(),s._viewMatrixDirty=!0,s._matrixNonIdentity=!0),s._opacity=1,s._colorize=[1,1,1],s._saoEnabled=!1!==r.saoEnabled,s._pbrEnabled=!1!==r.pbrEnabled,s._colorTextureEnabled=!1!==r.colorTextureEnabled,s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s._onCameraViewMatrix=s.scene.camera.on("matrix",(function(){s._viewMatrixDirty=!0})),s._meshesWithDirtyMatrices=[],s._numMeshesWithDirtyMatrices=0,s._onTick=s.scene.on("tick",(function(){for(;s._numMeshesWithDirtyMatrices>0;)s._meshesWithDirtyMatrices[--s._numMeshesWithDirtyMatrices]._updateMatrix()})),s._createDefaultTextureSet(),s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.colorize=r.colorize,s.opacity=r.opacity,s.backfaces=r.backfaces,s}return C(i,[{key:"_meshMatrixDirty",value:function(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}},{key:"_createDefaultTextureSet",value:function(){var e=new xc({id:"defaultColorTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new xc({id:"defaultMetalRoughTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new xc({id:"defaultNormalsTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new xc({id:"defaultEmissiveTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new xc({id:"defaultOcclusionTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Bc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"transforms",get:function(){return this._transforms}},{key:"textures",get:function(){return this._textures}},{key:"textureSets",get:function(){return this._textureSets}},{key:"meshes",get:function(){return this._meshes}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){}},{key:"matrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix},set:function(e){this._matrix.set(e||oh),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotationMatrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}},{key:"_rebuildMatrices",value:function(){this._matrixDirty&&($.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}},{key:"rotationMatrixConjugate",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}},{key:"_setWorldMatrixDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}},{key:"_sceneModelDirty",value:function(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(var e=0,t=this._entityList.length;e0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var l=e.colors,u=new Uint8Array(l.length),A=0,c=l.length;A>24&255,r=i>>16&255,n=i>>8&255,o=255&i;switch(e.pickColor=new Uint8Array([o,n,r,s]),e.solid="solid"===e.primitive,t.origin=$.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var i=0,s=e.buckets.length;i>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,n="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(s,".").concat(r),o=this._vboInstancingLayers[n];if(o)return o;for(var a=e.textureSet,l=e.geometry;!o;)switch(l.primitive){case"triangles":case"surface":o=new tl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":o=new tl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":o=new Ql({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":o=new Su({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[n]=o,this.layerList.push(o),o}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=$.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=$.createUUID()),void 0!==e.meshIds){var t=0;this._visible&&!1!==e.visible&&(t|=Ne),this._pickable&&!1!==e.pickable&&(t|=He),this._culled&&!1!==e.culled&&(t|=Qe),this._clippable&&!1!==e.clippable&&(t|=Ve),this._collidable&&!1!==e.collidable&&(t|=je),this._edges&&!1!==e.edges&&(t|=We),this._xrayed&&!1!==e.xrayed&&(t|=Ge),this._highlighted&&!1!==e.highlighted&&(t|=ze),this._selected&&!1!==e.selected&&(t|=Ke),e.flags=t,this._createEntity(e)}else this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],i=0,s=e.meshIds.length;it.sortId?1:0}));for(var o=0,a=this.layerList.length;o0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,i=this.layerList.length;t0){var t="".concat(this.id,"-dummyEntityForUnusedMeshes");this.warn('Creating dummy SceneModelEntity "'.concat(t,'" for unused SceneMeshes: [').concat(e.join(","),"]")),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(var n=0;n0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var i=this.scene.selectedMaterial._state;i.fill&&(i.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var s=this.scene.highlightMaterial._state;s.fill&&(s.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),s.edges&&(s.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e){for(var t=this.renderFlags,i=0,s=t.visibleLayers.length;i2&&void 0!==arguments[2]&&arguments[2],s=e.positionsCompressed||[],r=Hc(e.indices||[],t),n=Gc(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function s(i,s){return i!==e?e-i:s!==t?t-s:0}for(var r=0,o=(n.length>>1)-1;r<=o;){var a=o+r>>1,l=s(n[2*a],n[2*a+1]);if(l>0)r=a+1;else{if(!(l<0))return a;o=a-1}}return-r-1}var a=new Int32Array(n.length/2);a.fill(0);var l=s.length/3;if(l>8*(1<h.maxNumPositions&&(h=c()),h.bucketNumber>8)return[e];-1===u[v]&&(u[v]=h.numPositions++,h.positionsCompressed.push(s[3*v]),h.positionsCompressed.push(s[3*v+1]),h.positionsCompressed.push(s[3*v+2])),-1===u[g]&&(u[g]=h.numPositions++,h.positionsCompressed.push(s[3*g]),h.positionsCompressed.push(s[3*g+1]),h.positionsCompressed.push(s[3*g+2])),-1===u[m]&&(u[m]=h.numPositions++,h.positionsCompressed.push(s[3*m]),h.positionsCompressed.push(s[3*m+1]),h.positionsCompressed.push(s[3*m+2])),h.indices.push(u[v]),h.indices.push(u[g]),h.indices.push(u[m]);var _=void 0;(_=o(v,g))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(v,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(g,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]]))}var y=t/8*2,b=t/8,B=2*s.length+(r.length+n.length)*y,x=0;return s.length,A.forEach((function(e){x+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*b,e.positionsCompressed.length})),x>B?[e]:(i&&zc(A,e),A)}({positionsCompressed:s,indices:r,edgeIndices:n},s.length/3>65536?16:8):o=[{positionsCompressed:s,indices:r,edgeIndices:n}];return o}var Ah=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e,r))._positions=r.positions||[],r.indices)s._indices=r.indices;else{s._indices=[];for(var n=0,o=s._positions.length/3-1;n1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"BCFViewpoints",e,r)).originatingSystem=r.originatingSystem||"xeokit.io",s.authoringTool=r.authoringTool||"xeokit.io",s}return C(i,[{key:"getViewpoint",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=this.viewer.scene,s=i.camera,r=i.realWorldOffset,n=!0===t.reverseClippingPlanes,o={},a=$.normalizeVec3($.subVec3(s.look,s.eye,$.vec3())),l=s.eye,u=s.up;s.yUp&&(a=mh(a),l=mh(l),u=mh(u));var A=vh($.addVec3(l,r));"ortho"===s.projection?o.orthogonal_camera={camera_view_point:A,camera_direction:vh(a),camera_up_vector:vh(u),view_to_world_scale:s.ortho.scale}:o.perspective_camera={camera_view_point:A,camera_direction:vh(a),camera_up_vector:vh(u),field_of_view:s.perspective.fov};var c=i.sectionPlanes;for(var d in c)if(c.hasOwnProperty(d)){var p=c[d];if(!p.active)continue;var f=p.pos,v=void 0;v=n?$.negateVec3(p.dir,$.vec3()):p.dir,s.yUp&&(f=mh(f),v=mh(v)),$.addVec3(f,r),f=vh(f),v=vh(v),o.clipping_planes||(o.clipping_planes=[]),o.clipping_planes.push({location:f,direction:v})}var g=i.lineSets;for(var m in g)if(g.hasOwnProperty(m)){var _=g[m];o.lines||(o.lines=[]);for(var y=_.positions,b=_.indices,B=0,x=b.length/2;B1&&void 0!==arguments[1]?arguments[1]:{};if(e){var s=this.viewer,r=s.scene,n=r.camera,o=!1!==i.rayCast,a=!1!==i.immediate,l=!1!==i.reset,u=r.realWorldOffset,A=!0===i.reverseClippingPlanes;if(r.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.length>0&&e.clipping_planes.forEach((function(e){var t=gh(e.location,ch),i=gh(e.direction,ch);A&&$.negateVec3(i),$.subVec3(t,u),n.yUp&&(t=_h(t),i=_h(i)),new ln(r,{pos:t,dir:i})})),r.clearLines(),e.lines&&e.lines.length>0){var c=[],h=[],d=0;e.lines.forEach((function(e){e.start_point&&e.end_point&&(c.push(e.start_point.x),c.push(e.start_point.y),c.push(e.start_point.z),c.push(e.end_point.x),c.push(e.end_point.y),c.push(e.end_point.z),h.push(d++),h.push(d++))})),new Ah(r,{positions:c,indices:h,clippable:!1,collidable:!0})}if(r.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){var t=e.bitmap_type||"jpg",i=e.bitmap_data,s=gh(e.location,hh),o=gh(e.normal,dh),a=gh(e.up,ph),l=e.height||1;t&&i&&s&&o&&a&&(n.yUp&&(s=_h(s),o=_h(o),a=_h(a)),new Jn(r,{src:i,type:t,pos:s,normal:o,up:a,clippable:!1,collidable:!0,height:l}))})),l&&(r.setObjectsXRayed(r.xrayedObjectIds,!1),r.setObjectsHighlighted(r.highlightedObjectIds,!1),r.setObjectsSelected(r.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(r.setObjectsVisible(r.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!1}))}))):(r.setObjectsVisible(r.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!0}))})));var p=e.components.visibility.view_setup_hints;p&&(!1===p.spaces_visible&&r.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==p.spaces_translucent&&r.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),p.space_boundaries_visible,!1===p.openings_visible&&r.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),p.space_boundaries_translucent,void 0!==p.openings_translucent&&r.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(r.setObjectsSelected(r.selectedObjectIds,!1),e.components.selection.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.selected=!0}))}))),e.components.translucency&&(r.setObjectsXRayed(r.xrayedObjectIds,!1),e.components.translucency.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.xrayed=!0}))}))),e.components.coloring&&e.components.coloring.forEach((function(e){var s=e.color,r=0,n=!1;8===s.length&&((r=parseInt(s.substring(0,2),16)/256)<=1&&r>=.95&&(r=1),s=s.substring(2),n=!0);var o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((function(e){return t._withBCFComponent(i,e,(function(e){e.colorize=o,n&&(e.opacity=r)}))}))}))}if(e.perspective_camera||e.orthogonal_camera){var f,v,g,m;if(e.perspective_camera?(f=gh(e.perspective_camera.camera_view_point,ch),v=gh(e.perspective_camera.camera_direction,ch),g=gh(e.perspective_camera.camera_up_vector,ch),n.perspective.fov=e.perspective_camera.field_of_view,m="perspective"):(f=gh(e.orthogonal_camera.camera_view_point,ch),v=gh(e.orthogonal_camera.camera_direction,ch),g=gh(e.orthogonal_camera.camera_up_vector,ch),n.ortho.scale=e.orthogonal_camera.view_to_world_scale,m="ortho"),$.subVec3(f,u),n.yUp&&(f=_h(f),v=_h(v),g=_h(g)),o){var _=r.pick({pickSurface:!0,origin:f,direction:v});v=_?_.worldPos:$.addVec3(f,v,ch)}else v=$.addVec3(f,v,ch);a?(n.eye=f,n.look=v,n.up=g,n.projection=m):s.cameraFlight.flyTo({eye:f,look:v,up:g,duration:i.duration,projection:m})}}}},{key:"_withBCFComponent",value:function(e,t,i){var s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){var n=t.authoring_tool_id,o=r.objects[n];if(o)return void i(o);if(e.updateCompositeObjects)if(s.metaScene.metaObjects[n])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}if(t.ifc_guid){var a=t.ifc_guid,l=r.objects[a];if(l)return void i(l);if(e.updateCompositeObjects)if(s.metaScene.metaObjects[a])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(a),i);Object.keys(r.models).forEach((function(t){var n=$.globalizeObjectId(t,a),o=r.objects[n];o?i(o):e.updateCompositeObjects&&s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}))}}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this)}}]),i}();function vh(e){return{x:e[0],y:e[1],z:e[2]}}function gh(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function mh(e){return new Float64Array([e[0],-e[2],e[1]])}function _h(e){return new Float64Array([e[0],e[2],-e[1]])}function yh(e){var t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0")}var bh=$.vec3(),Bh=function(e,t,i,s){var r=e-i,n=t-s;return Math.sqrt(r*r+n*n)},xh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._eventSubs={};var n=s.plugin.viewer.scene;s._originMarker=new $e(n,r.origin),s._targetMarker=new $e(n,r.target),s._originWorld=$.vec3(),s._targetWorld=$.vec3(),s._wp=new Float64Array(24),s._vp=new Float64Array(24),s._pp=new Float64Array(24),s._cp=new Float64Array(8),s._xAxisLabelCulled=!1,s._yAxisLabelCulled=!1,s._zAxisLabelCulled=!1,s._color=r.color||s.plugin.defaultColor;var o=r.onMouseOver?function(e){r.onMouseOver(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},u=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},c=r.onContextMenu?function(e){r.onContextMenu(e,b(s))}:null,h=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};return s._originDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._targetDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._lengthWire=new et(s._container,{color:s._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._xAxisWire=new et(s._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._yAxisWire=new et(s._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._zAxisWire=new et(s._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._lengthLabel=new it(s._container,{fillColor:s._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._xAxisLabel=new it(s._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._yAxisLabel=new it(s._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._zAxisLabel=new it(s._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._sectionPlanesDirty=!0,s._visible=!1,s._originVisible=!1,s._targetVisible=!1,s._wireVisible=!1,s._axisVisible=!1,s._xAxisVisible=!1,s._yAxisVisible=!1,s._zAxisVisible=!1,s._axisEnabled=!0,s._labelsVisible=!1,s._labelsOnWires=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s._onMetricsUnits=n.metrics.on("units",(function(){s._cpDirty=!0,s._needUpdate()})),s._onMetricsScale=n.metrics.on("scale",(function(){s._cpDirty=!0,s._needUpdate()})),s._onMetricsOrigin=n.metrics.on("origin",(function(){s._cpDirty=!0,s._needUpdate()})),s._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){s._sectionPlanesDirty=!0,s._needUpdate()})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.targetVisible=r.targetVisible,s.wireVisible=r.wireVisible,s.axisVisible=r.axisVisible,s.xAxisVisible=r.xAxisVisible,s.yAxisVisible=r.yAxisVisible,s.zAxisVisible=r.zAxisVisible,s.labelsVisible=r.labelsVisible,s.labelsOnWires=r.labelsOnWires,s}return C(i,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}var t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var s=this._pp,r=this._cp,n=e.canvas.canvas.getBoundingClientRect(),o=this._container.getBoundingClientRect(),a=n.top-o.top,l=n.left-o.left,u=e.canvas.boundary,A=u[2],c=u[3],h=0,d=this.plugin.viewer.scene.metrics,p=d.scale,f=d.units,v=d.unitsInfo[f].abbrev,g=0,m=s.length;g1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e.viewer.scene)).pointerLens=r.pointerLens,s._active=!1,s._currentDistanceMeasurement=null,s._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},s._initMarkerDiv(),s._onCameraControlHoverSnapOrSurface=null,s._onCameraControlHoverSnapOrSurfaceOff=null,s._onMouseDown=null,s._onMouseUp=null,s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s._snapping=!1!==r.snapping,s._mouseState=0,s._attachPlugin(e,r),s}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this._markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.distanceMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this._markerDiv||this._initMarkerDiv(),this.fire("activated",!0);var t=this.distanceMeasurementsPlugin,i=this.scene,s=t.viewer.cameraControl,r=i.canvas.canvas;i.input;var n,o,a=!1,l=$.vec3(),u=$.vec2(),A=null;this._mouseState=0,this._onCameraControlHoverSnapOrSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){var i=t.snappedCanvasPos||t.canvasPos;if(a=!0,l.set(t.worldPos),u.set(t.canvasPos),0===e._mouseState){var s=r.getBoundingClientRect(),n=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,c=s.left+n,h=s.top+o;e._markerDiv.style.left="".concat(c+i[0]-5,"px"),e._markerDiv.style.top="".concat(h+i[1]-5,"px"),e._markerDiv.style.background="pink",t.snappedToVertex||t.snappedToEdge?(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,e.pointerLens.snapped=!0),e._markerDiv.style.background="greenyellow",e._markerDiv.style.border="2px solid green"):(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.canvasPos,e.pointerLens.snapped=!1),e._markerDiv.style.background="pink",e._markerDiv.style.border="2px solid red"),A=t.entity}else e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px";r.style.cursor="pointer",e._currentDistanceMeasurement&&(e._currentDistanceMeasurement.wireVisible=e._currentDistanceMeasurementInitState.wireVisible,e._currentDistanceMeasurement.axisVisible=e._currentDistanceMeasurementInitState.axisVisible&&e.distanceMeasurementsPlugin.defaultAxisVisible,e._currentDistanceMeasurement.xAxisVisible=e._currentDistanceMeasurementInitState.xAxisVisible&&e.distanceMeasurementsPlugin.defaultXAxisVisible,e._currentDistanceMeasurement.yAxisVisible=e._currentDistanceMeasurementInitState.yAxisVisible&&e.distanceMeasurementsPlugin.defaultYAxisVisible,e._currentDistanceMeasurement.zAxisVisible=e._currentDistanceMeasurementInitState.zAxisVisible&&e.distanceMeasurementsPlugin.defaultZAxisVisible,e._currentDistanceMeasurement.targetVisible=e._currentDistanceMeasurementInitState.targetVisible,e._currentDistanceMeasurement.target.worldPos=l.slice(),e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px")})),r.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(n=e.clientX,o=e.clientY)}),r.addEventListener("mouseup",this._onMouseUp=function(i){1===i.which&&(i.clientX>n+20||i.clientXo+20||i.clientY1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"DistanceMeasurements",e))._pointerLens=r.pointerLens,s._container=r.container||document.body,s._defaultControl=null,s._measurements={},s.labelMinAxisLength=r.labelMinAxisLength,s.defaultVisible=!1!==r.defaultVisible,s.defaultOriginVisible=!1!==r.defaultOriginVisible,s.defaultTargetVisible=!1!==r.defaultTargetVisible,s.defaultWireVisible=!1!==r.defaultWireVisible,s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.defaultAxisVisible=!1!==r.defaultAxisVisible,s.defaultXAxisVisible=!1!==r.defaultXAxisVisible,s.defaultYAxisVisible=!1!==r.defaultYAxisVisible,s.defaultZAxisVisible=!1!==r.defaultZAxisVisible,s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.zIndex=r.zIndex||1e4,s.defaultLabelsOnWires=!1!==r.defaultLabelsOnWires,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"pointerLens",get:function(){return this._pointerLens}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new Ph(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"labelMinAxisLength",get:function(){return this._labelMinAxisLength},set:function(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,s=t.target,r=new xh(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:t.visible,wireVisible:t.wireVisible,axisVisible:!1!==t.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==t.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==t.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==t.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==t.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:t.originVisible,targetVisible:t.targetVisible,color:t.color,labelsOnWires:!1!==t.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(function(){delete e._measurements[r.id]})),this.fire("measurementCreated",r),r}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,"FastNav",e))._hideColorTexture=!1!==r.hideColorTexture,s._hidePBR=!1!==r.hidePBR,s._hideSAO=!1!==r.hideSAO,s._hideEdges=!1!==r.hideEdges,s._hideTransparentObjects=!!r.hideTransparentObjects,s._scaleCanvasResolution=!!r.scaleCanvasResolution,s._scaleCanvasResolutionFactor=r.scaleCanvasResolutionFactor||.6,s._delayBeforeRestore=!1!==r.delayBeforeRestore,s._delayBeforeRestoreSeconds=r.delayBeforeRestoreSeconds||.5;var n=1e3*s._delayBeforeRestoreSeconds,o=!1,a=function(){n=1e3*s._delayBeforeRestoreSeconds,o||(e.scene._renderer.setColorTextureEnabled(!s._hideColorTexture),e.scene._renderer.setPBREnabled(!s._hidePBR),e.scene._renderer.setSAOEnabled(!s._hideSAO),e.scene._renderer.setTransparentEnabled(!s._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!s._hideEdges),s._scaleCanvasResolution?e.scene.canvas.resolutionScale=s._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,o=!0)},l=function(){e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),o=!1};s._onCanvasBoundary=e.scene.canvas.on("boundary",a),s._onCameraMatrix=e.scene.camera.on("matrix",a),s._onSceneTick=e.scene.on("tick",(function(e){o&&(n-=e.deltaTime,(!s._delayBeforeRestore||n<=0)&&l())}));var u=!1;return s._onSceneMouseDown=e.scene.input.on("mousedown",(function(){u=!0})),s._onSceneMouseUp=e.scene.input.on("mouseup",(function(){u=!1})),s._onSceneMouseMove=e.scene.input.on("mousemove",(function(){u&&a()})),s}return C(i,[{key:"hideColorTexture",get:function(){return this._hideColorTexture},set:function(e){this._hideColorTexture=e}},{key:"hidePBR",get:function(){return this._hidePBR},set:function(e){this._hidePBR=e}},{key:"hideSAO",get:function(){return this._hideSAO},set:function(e){this._hideSAO=e}},{key:"hideEdges",get:function(){return this._hideEdges},set:function(e){this._hideEdges=e}},{key:"hideTransparentObjects",get:function(){return this._hideTransparentObjects},set:function(e){this._hideTransparentObjects=!1!==e}},{key:"scaleCanvasResolution",get:function(){return this._scaleCanvasResolution},set:function(e){this._scaleCanvasResolution=e}},{key:"scaleCanvasResolutionFactor",get:function(){return this._scaleCanvasResolutionFactor},set:function(e){this._scaleCanvasResolutionFactor=e||.6}},{key:"delayBeforeRestore",get:function(){return this._delayBeforeRestore},set:function(e){this._delayBeforeRestore=e}},{key:"delayBeforeRestoreSeconds",get:function(){return this._delayBeforeRestoreSeconds},set:function(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),Fh=function(){function e(){w(this,e)}return C(e,[{key:"getMetaModel",value:function(e,t,i){le.loadJSON(e,(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLTF",value:function(e,t,i){le.loadArraybuffer(e,(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLB",value:function(e,t,i){le.loadArraybuffer(e,(function(e){t(e)}),(function(e){i(e)}))}},{key:"getArrayBuffer",value:function(e,t,i,s){!function(e,t,i,s){var r=function(){};i=i||r,s=s||r;var n=/^data:(.*?)(;base64)?,(.*)$/,o=t.match(n);if(o){var a=!!o[2],l=o[3];l=window.decodeURIComponent(l),a&&(l=window.atob(l));try{for(var u=new ArrayBuffer(l.length),A=new Uint8Array(u),c=0;c0&&void 0!==arguments[0]?arguments[0]:{};w(this,e),this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=t.messages,this.locale=t.locale}return C(e,[{key:"messages",set:function(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}},{key:"loadMessages",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e)this._messages[t]=e[t];this.messages=this._messages}},{key:"clearMessages",value:function(){this.messages={}}},{key:"locales",get:function(){return this._locales}},{key:"locale",get:function(){return this._locale},set:function(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}},{key:"translate",value:function(e,t){var i=this._messages[this._locale];if(!i)return null;var s=kh(e,i);return s?t?Ih(s,t):s:null}},{key:"translatePlurals",value:function(e,t,i){var s=this._messages[this._locale];if(!s)return null;var r=kh(e,s);return(r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one)?(r=Ih(r,[t]),i&&(r=Ih(r,i)),r):null}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);var s=this._eventSubs[e];if(s)for(var r in s){if(s.hasOwnProperty(r))s[r].callback(t)}}},{key:"on",value:function(e,t){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new Q),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});var i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);var s=this._eventSubIDMap.addItem();i[s]={callback:t},this._eventSubEvents[s]=e;var r=this._events[e];return void 0!==r&&t(r),s}},{key:"off",value:function(e){if(null!=e&&this._eventSubEvents){var t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];var i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}}]),e}();function kh(e,t){if(t[e])return t[e];for(var i=e.split("."),s=t,r=0,n=i.length;s&&r1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}var Dh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).t=r.t,s}return C(i,[{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"tangent",get:function(){return this.getTangent(this._t)}},{key:"length",get:function(){var e=this._getLengths();return e[e.length-1]}},{key:"getTangent",value:function(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),n=this.getPoint(s),o=$.subVec3(n,r,[]);return $.normalizeVec3(o,[])}},{key:"getPointAt",value:function(e){var t=this.getUToTMapping(e);return this.getPoint(t)}},{key:"getPoints",value:function(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}},{key:"_getLengths",value:function(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),n=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),n+=$.lenVec3($.subVec3(t,r,[])),s.push(n),r=t;return this.cacheArcLengths=s,s}},{key:"_updateArcLengths",value:function(){this.needsUpdate=!0,this._getLengths()}},{key:"getUToTMapping",value:function(e,t){var i,s=this._getLengths(),r=0,n=s.length;i=t||e*s[n-1];for(var o,a=0,l=n-1;a<=l;)if((o=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(o>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(n-1);var u=s[r];return(r+(i-u)/(s[r+1]-u))/(n-1)}}]),i}(),Sh=function(e){g(i,Dh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).points=r.points,s.t=r.t,s}return C(i,[{key:"points",get:function(){return this._points},set:function(e){this._points=e||[]}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,n=t[0===s?s:s-1],o=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],u=$.vec3();return u[0]=$.catmullRomInterpolate(n[0],o[0],a[0],l[0],r),u[1]=$.catmullRomInterpolate(n[1],o[1],a[1],l[1],r),u[2]=$.catmullRomInterpolate(n[2],o[2],a[2],l[2],r),u}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}},{key:"getJSON",value:function(){return{points:points,t:this._t}}}]),i}(),Th=$.vec3(),Rh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._frames=[],s._eyeCurve=new Sh(b(s)),s._lookCurve=new Sh(b(s)),s._upCurve=new Sh(b(s)),r.frames&&(s.addFrames(r.frames),s.smoothFrameTimes(1)),s}return C(i,[{key:"type",get:function(){return"CameraPath"}},{key:"frames",get:function(){return this._frames}},{key:"eyeCurve",get:function(){return this._eyeCurve}},{key:"lookCurve",get:function(){return this._lookCurve}},{key:"upCurve",get:function(){return this._upCurve}},{key:"saveFrame",value:function(e){var t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}},{key:"addFrame",value:function(e,t,i,s){var r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}},{key:"addFrames",value:function(e){for(var t,i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Th),t.look=this._lookCurve.getPoint(e,Th),t.up=this._upCurve.getPoint(e,Th)}},{key:"sampleFrame",value:function(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}},{key:"smoothFrameTimes",value:function(e){if(0!==this._frames.length){var t=$.vec3(),i=0;this._frames[0].t=0;for(var s=[],r=1,n=this._frames.length;r1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._look1=$.vec3(),s._eye1=$.vec3(),s._up1=$.vec3(),s._look2=$.vec3(),s._eye2=$.vec3(),s._up2=$.vec3(),s._orthoScale1=1,s._orthoScale2=1,s._flying=!1,s._flyEyeLookUp=!1,s._flyingEye=!1,s._flyingLook=!1,s._callback=null,s._callbackScope=null,s._time1=null,s._time2=null,s.easing=!1!==r.easing,s.duration=r.duration,s.fit=r.fit,s.fitFOV=r.fitFOV,s.trail=r.trail,s}return C(i,[{key:"type",get:function(){return"CameraFlightAnimation"}},{key:"flyTo",value:function(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;var s,r,n,o,a,l=this.scene.camera,u=!!e.projection&&e.projection!==l.projection;if(this._eye1[0]=l.eye[0],this._eye1[1]=l.eye[1],this._eye1[2]=l.eye[2],this._look1[0]=l.look[0],this._look1[1]=l.look[1],this._look1[2]=l.look[2],this._up1[0]=l.up[0],this._up1[1]=l.up[1],this._up1[2]=l.up[2],this._orthoScale1=l.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye&&e.look||e.up)r=e.eye,n=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)n=e.look;else{var A=e;if((le.isNumeric(A)||le.isString(A))&&(a=A,!(A=this.scene.components[a])))return this.error("Component not found: "+le.inQuotes(a)),void(t&&(i?t.call(i):t()));u||(s=A.aabb||this.scene.aabb)}var c=e.poi;if(s){if(s[3]=1;e>1&&(e=1);var s=this.easing?i._ease(e,0,1,1):e,r=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?($.subVec3(r.eye,r.look,Qh),r.eye=$.lerpVec3(s,0,1,this._eye1,this._eye2,Oh),r.look=$.subVec3(Oh,Qh,Uh)):this._flyingLook&&(r.look=$.lerpVec3(s,0,1,this._look1,this._look2,Uh),r.up=$.lerpVec3(s,0,1,this._up1,this._up2,Nh)):this._flyingEyeLookUp&&(r.eye=$.lerpVec3(s,0,1,this._eye1,this._eye2,Oh),r.look=$.lerpVec3(s,0,1,this._look1,this._look2,Uh),r.up=$.lerpVec3(s,0,1,this._up1,this._up2,Nh)),this._projection2){var n="ortho"===this._projection2?i._easeOutExpo(e,0,1,1):i._easeInCubic(e,0,1,1);r.customProjection.matrix=$.lerpMat4(n,0,1,this._projMatrix1,this._projMatrix2)}else r.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return r.ortho.scale=this._orthoScale2,void this.stop();_e.scheduleTask(this._update,this)}}},{key:"stop",value:function(){if(this._flying){this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);var e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}}},{key:"cancel",value:function(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}},{key:"duration",get:function(){return this._duration/1e3},set:function(e){this._duration=e?1e3*e:500,this.stop()}},{key:"fit",get:function(){return this._fit},set:function(e){this._fit=!1!==e}},{key:"fitFOV",get:function(){return this._fitFOV},set:function(e){this._fitFOV=e||45}},{key:"trail",get:function(){return this._trail},set:function(e){this._trail=!!e}},{key:"destroy",value:function(){this.stop(),f(B(i.prototype),"destroy",this).call(this)}}],[{key:"_ease",value:function(e,t,i,s){return-i*(e/=s)*(e-2)+t}},{key:"_easeInCubic",value:function(e,t,i,s){return i*(e/=s)*e*e+t}},{key:"_easeOutExpo",value:function(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}}]),i}(),Vh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._cameraFlightAnimation=new Hh(b(s)),s._t=0,s.state=i.SCRUBBING,s._playingFromT=0,s._playingToT=0,s._playingRate=r.playingRate||1,s._playingDir=1,s._lastTime=null,s.cameraPath=r.cameraPath,s._tick=s.scene.on("tick",s._updateT,b(s)),s}return C(i,[{key:"type",get:function(){return"CameraPathAnimation"}},{key:"_updateT",value:function(){var e=this._cameraPath;if(e){var t,s,r=performance.now(),n=this._lastTime?.001*(r-this._lastTime):0;if(this._lastTime=r,0!==n)switch(this.state){case i.SCRUBBING:return;case i.PLAYING:if(this._t+=this._playingRate*n,0===(t=this._cameraPath.frames.length)||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=i.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case i.PLAYING_TO:s=this._t+this._playingRate*n*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=i.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}}},{key:"_ease",value:function(e,t,i,s){return-i*(e/=s)*(e-2)+t}},{key:"cameraPath",get:function(){return this._cameraPath},set:function(e){this._cameraPath=e}},{key:"rate",get:function(){return this._playingRate},set:function(e){this._playingRate=e}},{key:"play",value:function(){this._cameraPath&&(this._lastTime=null,this.state=i.PLAYING)}},{key:"playToT",value:function(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=i.PLAYING_TO)}},{key:"playToFrame",value:function(e){var t=this._cameraPath;if(t){var i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}}},{key:"flyToFrame",value:function(e,t){var s=this._cameraPath;if(s){var r=s.frames[e];r?(this.state=i.SCRUBBING,this._cameraFlightAnimation.flyTo(r,t)):this.error("flyToFrame - frame index out of range: "+e)}}},{key:"scrubToT",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=i.SCRUBBING))}},{key:"scrubToFrame",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(t.frames[e]?(t.loadFrame(this._t),this.state=i.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)))}},{key:"stop",value:function(){this.state=i.SCRUBBING,this.fire("stopped")}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene.off(this._tick)}}]),i}();Vh.STOPPED=0,Vh.SCRUBBING=1,Vh.PLAYING=2,Vh.PLAYING_TO=3;var jh=$.vec3(),Gh=$.vec3();$.vec3();var zh=$.vec3([0,-1,0]),Kh=$.vec4([0,0,0,1]),Wh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._src=null,s._image=null,s._pos=$.vec3(),s._origin=$.vec3(),s._rtcPos=$.vec3(),s._dir=$.vec3(),s._size=1,s._imageSize=$.vec2(),s._texture=new Tn(b(s)),s._plane=new en(b(s),{geometry:new Ii(b(s),zn({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Li(b(s),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:s._texture,emissiveMap:s._texture,backfaces:!0}),clippable:r.clippable}),s._grid=new en(b(s),{geometry:new Ii(b(s),Gn({size:1,divisions:10})),material:new Li(b(s),{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:r.clippable}),s._node=new mn(b(s),{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[s._plane,s._grid]}),s._gridVisible=!1,s.visible=!0,s.gridVisible=r.gridVisible,s.position=r.position,s.rotation=r.rotation,s.dir=r.dir,s.size=r.size,s.collidable=r.collidable,s.clippable=r.clippable,s.pickable=r.pickable,s.opacity=r.opacity,r.image?s.image=r.image:s.src=r.src,s}return C(i,[{key:"visible",get:function(){return this._plane.visible},set:function(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}},{key:"gridVisible",get:function(){return this._gridVisible},set:function(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"position",get:function(){return this._pos},set:function(e){this._pos.set(e||[0,0,0]),Re(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}},{key:"rotation",get:function(){return this._node.rotation},set:function(e){this._node.rotation=e}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"dir",get:function(){return this._dir},set:function(e){if(this._dir.set(e||[0,0,-1]),e){var t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];$.subVec3(t,this.position,jh);var s=-$.dotVec3(i,jh);$.normalizeVec3(i),$.mulVec3Scalar(i,s,Gh),$.vec3PairToQuaternion(zh,e,Kh),this._node.quaternion=Kh}}},{key:"collidable",get:function(){return this._node.collidable},set:function(e){this._node.collidable=!1!==e}},{key:"clippable",get:function(){return this._node.clippable},set:function(e){this._node.clippable=!1!==e}},{key:"pickable",get:function(){return this._node.pickable},set:function(e){this._node.pickable=!1!==e}},{key:"opacity",get:function(){return this._node.opacity},set:function(e){this._node.opacity=e}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this)}},{key:"_updatePlaneSizeFromImage",value:function(){var e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){var s=i/t;this._node.scale=[e,1,e*s]}else{var r=t/i;this._node.scale=[e*r,1,e]}}}]),i}(),Xh=function(e){g(i,gi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i);var n=b(s=t.call(this,e,r));s._shadowRenderBuf=null,s._shadowViewMatrix=null,s._shadowProjMatrix=null,s._shadowViewMatrixDirty=!0,s._shadowProjMatrixDirty=!0;var o=s.scene.camera,a=s.scene.canvas;return s._onCameraViewMatrix=o.on("viewMatrix",(function(){s._shadowViewMatrixDirty=!0})),s._onCameraProjMatrix=o.on("projMatrix",(function(){s._shadowProjMatrixDirty=!0})),s._onCanvasBoundary=a.on("boundary",(function(){s._shadowProjMatrixDirty=!0})),s._state=new Jt({type:"point",pos:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:r.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(n._shadowViewMatrixDirty){n._shadowViewMatrix||(n._shadowViewMatrix=$.identityMat4());var e=n._state.pos,t=o.look,i=o.up;$.lookAtMat4v(e,t,i,n._shadowViewMatrix),n._shadowViewMatrixDirty=!1}return n._shadowViewMatrix},getShadowProjMatrix:function(){if(n._shadowProjMatrixDirty){n._shadowProjMatrix||(n._shadowProjMatrix=$.identityMat4());var e=n.scene.canvas.canvas;$.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,n._shadowProjMatrix),n._shadowProjMatrixDirty=!1}return n._shadowProjMatrix},getShadowRenderBuf:function(){return n._shadowRenderBuf||(n._shadowRenderBuf=new jt(n.scene.canvas.canvas,n.scene.canvas.gl,{size:[1024,1024]})),n._shadowRenderBuf}}),s.pos=r.pos,s.color=r.color,s.intensity=r.intensity,s.constantAttenuation=r.constantAttenuation,s.linearAttenuation=r.linearAttenuation,s.quadraticAttenuation=r.quadraticAttenuation,s.castsShadow=r.castsShadow,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"PointLight"}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"constantAttenuation",get:function(){return this._state.attenuation[0]},set:function(e){this._state.attenuation[0]=e||0,this.glRedraw()}},{key:"linearAttenuation",get:function(){return this._state.attenuation[1]},set:function(e){this._state.attenuation[1]=e||0,this.glRedraw()}},{key:"quadraticAttenuation",get:function(){return this._state.attenuation[2]},set:function(e){this._state.attenuation[2]=e||0,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}();function Jh(e){return 0==(e&e-1)}function Yh(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var Zh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i);var n=(s=t.call(this,e,r)).scene.canvas.gl;return s._state=new Jt({texture:new Fn({gl:n,target:n.TEXTURE_CUBE_MAP}),flipY:s._checkFlipY(r.minFilter),encoding:s._checkEncoding(r.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),s._src=r.src,s._images=[],s._loadSrc(r.src),se.memory.textures++,s}return C(i,[{key:"type",get:function(){return"CubeTexture"}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}},{key:"_loadSrc",value:function(e){var t=this,i=this.scene.canvas.gl;this._images=[];for(var s=!1,r=0,n=function(n){var o,a,l=new Image;l.onload=(o=l,a=n,function(){if(!s&&(o=function(e){if(!Jh(e.width)||!Jh(e.height)){var t=document.createElement("canvas");t.width=Yh(e.width),t.height=Yh(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}(o),t._images[a]=o,6==++r)){var e=t._state.texture;e||(e=new Fn({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}),l.onerror=function(){s=!0},l.src=e[n]},o=0;o1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).scene._lightsState.addReflectionMap(s._state),s.scene._reflectionMapCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"ReflectionMap"}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._reflectionMapDestroyed(this)}}]),i}(),$h=function(e){g(i,Zh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).scene._lightMapCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"LightMap"}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._lightMapDestroyed(this)}}]),i}(),ed=function(e){g(i,$e);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,{entity:r.entity,occludable:r.occludable,worldPos:r.worldPos}))._occluded=!1,s._visible=!0,s._src=null,s._image=null,s._pos=$.vec3(),s._origin=$.vec3(),s._rtcPos=$.vec3(),s._dir=$.vec3(),s._size=1,s._imageSize=$.vec2(),s._texture=new Tn(b(s),{src:r.src}),s._geometry=new Ii(b(s),{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),s._mesh=new en(b(s),{geometry:s._geometry,material:new Li(b(s),{ambient:[.9,.3,.9],shininess:30,diffuseMap:s._texture,backfaces:!0}),scale:[1,1,1],position:r.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),s.visible=!0,s.collidable=r.collidable,s.clippable=r.clippable,s.pickable=r.pickable,s.opacity=r.opacity,s.size=r.size,r.image?s.image=r.image:s.src=r.src,s}return C(i,[{key:"_setVisible",value:function(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,f(B(i.prototype),"_setVisible",this).call(this,e)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"collidable",get:function(){return this._mesh.collidable},set:function(e){this._mesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._mesh.clippable},set:function(e){this._mesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._mesh.pickable},set:function(e){this._mesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._mesh.opacity},set:function(e){this._mesh.opacity=e}},{key:"_updatePlaneSizeFromImage",value:function(){var e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}]),i}(),td=function(){function e(t){w(this,e),this._eye=$.vec3(),this._look=$.vec3(),this._up=$.vec3(),this._projection={},t&&this.saveCamera(t)}return C(e,[{key:"saveCamera",value:function(e){var t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}},{key:"restoreCamera",value:function(e,t){var i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(function(){r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}]),e}(),id=$.vec3(),sd=function(){function e(t){if(w(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,t){var i=t.metaScene.scene;this.saveObjects(i,t)}}return C(e,[{key:"saveObjects",value:function(e,t,i){this.numObjects=0,this._mask=i?le.apply(i,{}):null;for(var s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,A=!i||i.colorize,c=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).v0=r.v0,s.v1=r.v1,s.v2=r.v2,s.v3=r.v3,s.t=r.t,s}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"v3",get:function(){return this._v3},set:function(e){this.fire("v3",this._v3=e||$.vec3([0,0,0]))}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=$.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=$.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}]),i}(),ad=function(e){g(i,Dh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._cachedLengths=[],s._dirty=!0,s._curves=[],s._t=0,s._dirtySubs=[],s._destroyedSubs=[],s.curves=r.curves||[],s.t=r.t,s}return C(i,[{key:"addCurve",value:function(e){this._curves.push(e),this._dirty=!0}},{key:"curves",get:function(){return this._curves},set:function(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"length",get:function(){var e=this._getCurveLengths();return e[e.length-1]}},{key:"getPoint",value:function(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var n=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(n)}r++}return null}},{key:"_getCurveLengths",value:function(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).v0=r.v0,s.v1=r.v1,s.v2=r.v2,s.t=r.t,s}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=$.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=$.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}]),i}(),ud=function(e){g(i,lh);var t=_(i);function i(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),t.call(this,e,s)}return C(i)}(),Ad=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._skyboxMesh=new en(b(s),{geometry:new Ii(b(s),{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Li(b(s),{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Tn(b(s),{src:r.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:r.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),s.size=r.size,s.active=r.active,s}return C(i,[{key:"size",get:function(){return this._size},set:function(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}},{key:"active",get:function(){return this._skyboxMesh.visible},set:function(e){this._skyboxMesh.visible=e}}]),i}(),cd=function(){function e(){w(this,e)}return C(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),hd=$.vec4(),dd=$.vec4(),pd=$.vec3(),fd=$.vec3(),vd=$.vec3(),gd=$.vec4(),md=$.vec4(),_d=$.vec4(),yd=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"dollyToCanvasPos",value:function(e,t,i){var s=!1,r=this._scene.camera;if(e){var n=$.subVec3(e,r.eye,pd);s=$.lenVec3(n)0&&void 0!==arguments[0]?arguments[0]:{};this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);var t=e.color||[1,0,0];this._pivotSphereMaterial=new Li(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}},{key:"disablePivotSphere",value:function(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}},{key:"startPivot",value:function(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;var e=this._scene.camera,t=$.lookAtMat4v(e.eye,e.look,e.worldUp);$.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var i=this.getPivotPos();this._cameraOffset[2]+=$.distVec3(e.eye,i),t=$.inverseMat4(t);var s=$.transformVec3(t,this._cameraOffset),r=$.vec3();if($.subVec3(e.eye,i,r),$.addVec3(r,s),e.zUp){var n=r[1];r[1]=r[2],r[2]=n}this._radius=$.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=$.normalizeVec3($.subVec3(e.look,e.eye,bd)),i=$.cross3Vec3(t,e.worldUp,Bd);return $.sqLenVec3(i)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,i=Math.abs($.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),o=[0,0,-1,1],a=$.dotVec4(o,r)/$.dotVec4(o,n),l=wd;t.project.unproject(e,a,Pd,Cd,l);var u=$.normalizeVec3($.subVec3(l,t.eye,bd)),A=$.addVec3(t.eye,$.mulVec3Scalar(u,i,Bd),xd);this.setPivotPos(A)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var i=this._scene.camera,s=-e,r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=$.clamp(this._polar,.001,Math.PI-.001);var n=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){var o=n[1];n[1]=n[2],n[2]=o}var a=$.lenVec3($.subVec3(i.look,i.eye,$.vec3())),l=this.getPivotPos();$.addVec3(n,l);var u=$.lookAtMat4v(n,l,i.worldUp);u=$.inverseMat4(u);var A=$.transformVec3(u,this._cameraOffset);u[12]-=A[0],u[13]-=A[1],u[14]-=A[2];var c=[u[8],u[9],u[10]];i.eye=[u[12],u[13],u[14]],$.subVec3(i.eye,$.mulVec3Scalar(c,a),i.look),i.up=[u[4],u[5],u[6]],this.showPivot()}}},{key:"showPivot",value:function(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}},{key:"hidePivot",value:function(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),Fd=function(){function e(t,i){w(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=i,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=$.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}return C(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){var e="".concat(~~this.pickCursorPos[0],"-").concat(~~this.pickCursorPos[1],"-").concat(this.scheduleSnapOrPick,"-").concat(this.schedulePickSurface,"-").concat(this.schedulePickEntity);if(this._lastHash!==e){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;var t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var i=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});i&&(i.snappedToEdge||i.snappedToVertex)?(this.snapPickResult=i,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var s=this.pickResult.canvasPos;if(s[0]===this.pickCursorPos[0]&&s[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var r=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}}},{key:"fireEvents",value:function(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new bt;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}]),e}(),Ed=$.vec2(),kd=function(){function e(t,i,s,r,n){w(this,e),this._scene=t;var o,a,l,u=i.pickController,A=0,c=0,h=0,d=0,p=!1,f=$.vec3(),v=!0,g=this._scene.canvas.canvas,m=[];function _(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];g.style.cursor="move",y(),e&&b()}function y(){A=r.pointerCanvasPos[0],c=r.pointerCanvasPos[1],h=r.pointerCanvasPos[0],d=r.pointerCanvasPos[1]}function b(){u.pickCursorPos=r.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(p=!0,f.set(u.pickResult.worldPos)):p=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!1}}),g.addEventListener("mousedown",this._mouseDownHandler=function(e){if(s.active&&s.pointerEnabled)switch(e.which){case 1:m[t.input.KEY_SHIFT]||s.planView?(o=!0,_()):(o=!0,_(!1));break;case 2:a=!0,_();break;case 3:l=!0,s.panRightClick&&_()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(){if(s.active&&s.pointerEnabled&&(o||a||l)){var e=t.canvas.boundary,i=e[2],u=e[3],h=r.pointerCanvasPos[0],d=r.pointerCanvasPos[1];if(m[t.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l){var v=h-A,g=d-c,_=t.camera;if("perspective"===_.projection){var y=Math.abs(p?$.lenVec3($.subVec3(f,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(_.perspective.fov/2*Math.PI/180);n.panDeltaX+=1.5*v*y/u,n.panDeltaY+=1.5*g*y/u}else n.panDeltaX+=.5*_.ortho.scale*(v/u),n.panDeltaY+=.5*_.ortho.scale*(g/u)}else!o||a||l||s.planView||(s.firstPerson?(n.rotateDeltaY-=(h-A)/i*s.dragRotationRate/2,n.rotateDeltaX+=(d-c)/u*(s.dragRotationRate/4)):(n.rotateDeltaY-=(h-A)/i*(1.5*s.dragRotationRate),n.rotateDeltaX+=(d-c)/u*(1.5*s.dragRotationRate)));A=h,c=d}}),g.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){s.active&&s.pointerEnabled&&r.mouseover&&(v=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:o=!1,a=!1,l=!1}}),g.addEventListener("mouseup",this._mouseUpHandler=function(e){if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var i=e.target,s=0,r=0,n=0,o=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,n+=i.scrollLeft,o+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+n-s,t[1]=e.pageY+o-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Ed);var t=Ed[0],r=Ed[1];Math.abs(t-h)<3&&Math.abs(r-d)<3&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Ed,event:e},!0)}g.style.removeProperty("cursor")}}),g.addEventListener("mouseenter",this._mouseEnterHandler=function(){s.active&&s.pointerEnabled});var B=1/60,x=null;g.addEventListener("wheel",this._mouseWheelHandler=function(e){if(s.active&&s.pointerEnabled){var t=performance.now()/1e3,i=null!==x?t-x:0;x=t,i>.05&&(i=.05),i0?i.cameraFlight.flyTo(Ld,(function(){i.pivotController.getPivoting()&&s.followPointer&&i.pivotController.showPivot()})):(i.cameraFlight.jumpTo(Ld),i.pivotController.getPivoting()&&s.followPointer&&i.pivotController.showPivot())}}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),Od=function(){function e(t,i,s,r,n){var o=this;w(this,e),this._scene=t;var a=i.pickController,l=i.pivotController,u=i.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;var A=!1,c=!1,h=this._scene.canvas.canvas,d=function(e){var s;e&&e.worldPos&&(s=e.worldPos);var r=e&&e.entity?e.entity.aabb:t.aabb;if(s){var n=t.camera;$.subVec3(n.eye,n.look,[]),i.cameraFlight.flyTo({aabb:r})}else i.cameraFlight.flyTo({aabb:r})},p=t.tickify(this._canvasMouseMoveHandler=function(e){if(s.active&&s.pointerEnabled&&!A&&!c){var i=u.hasSubs("hover"),n=u.hasSubs("hoverEnter"),l=u.hasSubs("hoverOut"),h=u.hasSubs("hoverOff"),d=u.hasSubs("hoverSurface"),p=u.hasSubs("hoverSnapOrSurface");if(i||n||l||h||d||p)if(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=d,a.scheduleSnapOrPick=p,a.update(),a.pickResult){if(a.pickResult.entity){var f=a.pickResult.entity.id;o._lastPickedEntityId!==f&&(void 0!==o._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),u.fire("hoverEnter",a.pickResult,!0),o._lastPickedEntityId=f)}u.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&u.fire("hoverSurface",a.pickResult,!0)}else void 0!==o._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),o._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}});h.addEventListener("mousemove",p),h.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(A=!0),3===e.which&&(c=!0),1===e.which&&s.active&&s.pointerEnabled&&(r.mouseDownClientX=e.clientX,r.mouseDownClientY=e.clientY,r.mouseDownCursorX=r.pointerCanvasPos[0],r.mouseDownCursorY=r.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===e.which))){var i=a.pickResult;i&&i.worldPos?(l.setPivotPos(i.worldPos),l.startPivot()):(s.smartPivot?l.setCanvasPivotPos(r.pointerCanvasPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(A=!1),3===e.which&&(c=!1),l.getPivoting()&&l.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(s.active&&s.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-r.mouseDownClientX)>3||Math.abs(e.clientY-r.mouseDownClientY)>3)))){var n=u.hasSubs("picked"),A=u.hasSubs("pickedNothing"),c=u.hasSubs("pickedSurface"),h=u.hasSubs("doublePicked"),p=u.hasSubs("doublePickedSurface"),f=u.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||h||p||f))return(n||A||c)&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=c,a.update(),a.pickResult?(u.fire("picked",a.pickResult,!0),a.pickedSurface&&u.fire("pickedSurface",a.pickResult,!0)):u.fire("pickedNothing",{canvasPos:r.pointerCanvasPos},!0)),void(o._clicks=0);if(o._clicks++,1===o._clicks){a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo,a.schedulePickSurface=c,a.update();var v=a.pickResult,g=a.pickedSurface;o._timeout=setTimeout((function(){v?(u.fire("picked",v,!0),g&&(u.fire("pickedSurface",v,!0),!s.firstPerson&&s.followPointer&&(i.pivotController.setPivotPos(v.worldPos),i.pivotController.startPivot()&&i.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:r.pointerCanvasPos},!0),o._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==o._timeout&&(window.clearTimeout(o._timeout),o._timeout=null),a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo||h||p,a.schedulePickSurface=a.schedulePickEntity&&p,a.update(),a.pickResult){if(u.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&u.fire("doublePickedSurface",a.pickResult,!0),s.doublePickFlyTo&&(d(a.pickResult),!s.firstPerson&&s.followPointer)){var m=a.pickResult.entity.aabb,_=$.getAABB3Center(m);i.pivotController.setPivotPos(_),i.pivotController.startPivot()&&i.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:r.pointerCanvasPos},!0),s.doublePickFlyTo&&(d(),!s.firstPerson&&s.followPointer)){var y=t.aabb,b=$.getAABB3Center(y);i.pivotController.setPivotPos(b),i.pivotController.startPivot()&&i.pivotController.showPivot()}o._clicks=0}}},!1)}return C(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Nd=function(){function e(t,i,s,r,n){w(this,e),this._scene=t;var o=t.input,a=[],l=t.canvas.canvas,u=!0;this._onSceneMouseMove=o.on("mousemove",(function(){u=!0})),this._onSceneKeyDown=o.on("keydown",(function(e){s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&r.mouseover&&(a[e]=!0,e===o.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(function(e){s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&(a[e]=!1,e===o.KEY_SHIFT&&(l.style.cursor=null),i.pivotController.getPivoting()&&i.pivotController.endPivot())})),this._onTick=t.on("tick",(function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&r.mouseover){var l=i.cameraControl,A=e.deltaTime/1e3;if(!s.planView){var c=l._isKeyDownForAction(l.ROTATE_Y_POS,a),h=l._isKeyDownForAction(l.ROTATE_Y_NEG,a),d=l._isKeyDownForAction(l.ROTATE_X_POS,a),p=l._isKeyDownForAction(l.ROTATE_X_NEG,a),f=A*s.keyboardRotationRate;(c||h||d||p)&&(!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),c?n.rotateDeltaY+=f:h&&(n.rotateDeltaY-=f),d?n.rotateDeltaX+=f:p&&(n.rotateDeltaX-=f),!s.firstPerson&&s.followPointer&&i.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){var v=l._isKeyDownForAction(l.DOLLY_BACKWARDS,a),g=l._isKeyDownForAction(l.DOLLY_FORWARDS,a);if(v||g){var m=A*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),g?n.dollyDelta-=m:v&&(n.dollyDelta+=m),u&&(r.followPointerDirty=!0,u=!1)}}var _=l._isKeyDownForAction(l.PAN_FORWARDS,a),y=l._isKeyDownForAction(l.PAN_BACKWARDS,a),b=l._isKeyDownForAction(l.PAN_LEFT,a),B=l._isKeyDownForAction(l.PAN_RIGHT,a),x=l._isKeyDownForAction(l.PAN_UP,a),w=l._isKeyDownForAction(l.PAN_DOWN,a),P=(a[o.KEY_ALT]?.3:1)*A*s.keyboardPanRate;(_||y||b||B||x||w)&&(!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),w?n.panDeltaY+=P:x&&(n.panDeltaY+=-P),B?n.panDeltaX+=-P:b&&(n.panDeltaX+=P),y?n.panDeltaZ+=P:_&&(n.panDeltaZ+=-P))}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),Qd=$.vec3(),Hd=function(){function e(t,i,s,r,n){w(this,e),this._scene=t;var o=t.camera,a=i.pickController,l=i.pivotController,u=i.panController,A=1,c=1,h=null;this._onTick=t.on("tick",(function(){if(s.active&&s.pointerEnabled){var e="default";if(Math.abs(n.dollyDelta)<.001&&(n.dollyDelta=0),Math.abs(n.rotateDeltaX)<.001&&(n.rotateDeltaX=0),Math.abs(n.rotateDeltaY)<.001&&(n.rotateDeltaY=0),0===n.rotateDeltaX&&0===n.rotateDeltaY||(n.dollyDelta=0),s.followPointer&&--A<=0&&(A=1,0!==n.dollyDelta)){if(0===n.rotateDeltaY&&0===n.rotateDeltaX&&s.followPointer&&r.followPointerDirty&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?h=a.pickResult.worldPos:(c=1,h=null),r.followPointerDirty=!1),h){var i=Math.abs($.lenVec3($.subVec3(h,t.camera.eye,Qd)));c=i/s.dollyProximityThreshold}cs.longTapRadius||Math.abs(g)>s.longTapRadius)&&(clearTimeout(r.longTouchTimeout),r.longTouchTimeout=null),s.planView){var m=t.camera;if("perspective"===m.projection){var _=Math.abs(t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);n.panDeltaX+=v*_/l*s.touchPanRate,n.panDeltaY+=g*_/l*s.touchPanRate}else n.panDeltaX+=.5*m.ortho.scale*(v/l)*s.touchPanRate,n.panDeltaY+=.5*m.ortho.scale*(g/l)*s.touchPanRate}else n.rotateDeltaY-=v/a*(1*s.dragRotationRate),n.rotateDeltaX+=g/l*(1.5*s.dragRotationRate)}else if(2===p){var y=d[0],b=d[1];Gd(y,u),Gd(b,A);var B=$.geometricMeanVec2(h[0],h[1]),x=$.geometricMeanVec2(u,A),w=$.vec2();$.subVec2(B,x,w);var P=w[0],C=w[1],M=t.camera,F=$.distVec2([y.pageX,y.pageY],[b.pageX,b.pageY]),E=($.distVec2(h[0],h[1])-F)*s.touchDollyRate;if(n.dollyDelta=E,Math.abs(E)<1)if("perspective"===M.projection){var k=o.pickResult?o.pickResult.worldPos:t.center,I=Math.abs($.lenVec3($.subVec3(k,t.camera.eye,[])))*Math.tan(M.perspective.fov/2*Math.PI/180);n.panDeltaX-=P*I/l*s.touchPanRate,n.panDeltaY-=C*I/l*s.touchPanRate}else n.panDeltaX-=.5*M.ortho.scale*(P/l)*s.touchPanRate,n.panDeltaY-=.5*M.ortho.scale*(C/l)*s.touchPanRate;r.pointerCanvasPos=x}for(var D=0;D-1&&t-c<150&&(h>-1&&c-h<325?(Kd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("doublePicked",a.pickResult),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult),s.doublePickFlyTo&&p(a.pickResult)):(l.fire("doublePickedNothing"),s.doublePickFlyTo&&p()),h=-1):$.distVec2(u[0],A)<4&&(Kd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("picked",a.pickResult),a.pickedSurface&&l.fire("pickedSurface",a.pickResult)):l.fire("pickedNothing"),h=t),c=-1),u.length=i.length;for(var d=0,f=i.length;d1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r)).PAN_LEFT=0,s.PAN_RIGHT=1,s.PAN_UP=2,s.PAN_DOWN=3,s.PAN_FORWARDS=4,s.PAN_BACKWARDS=5,s.ROTATE_X_POS=6,s.ROTATE_X_NEG=7,s.ROTATE_Y_POS=8,s.ROTATE_Y_NEG=9,s.DOLLY_FORWARDS=10,s.DOLLY_BACKWARDS=11,s.AXIS_VIEW_RIGHT=12,s.AXIS_VIEW_BACK=13,s.AXIS_VIEW_LEFT=14,s.AXIS_VIEW_FRONT=15,s.AXIS_VIEW_TOP=16,s.AXIS_VIEW_BOTTOM=17,s._keyMap={},s.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},s._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},s._states={pointerCanvasPos:$.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:$.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},s._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var n=s.scene;return s._controllers={cameraControl:b(s),pickController:new Fd(b(s),s._configs),pivotController:new Md(n,s._configs),panController:new yd(n),cameraFlight:new Hh(b(s),{duration:.5})},s._handlers=[new Vd(s.scene,s._controllers,s._configs,s._states,s._updates),new zd(s.scene,s._controllers,s._configs,s._states,s._updates),new kd(s.scene,s._controllers,s._configs,s._states,s._updates),new Ud(s.scene,s._controllers,s._configs,s._states,s._updates),new Od(s.scene,s._controllers,s._configs,s._states,s._updates),new Wd(s.scene,s._controllers,s._configs,s._states,s._updates),new Nd(s.scene,s._controllers,s._configs,s._states,s._updates)],s._cameraUpdater=new Hd(s.scene,s._controllers,s._configs,s._states,s._updates),s.navMode=r.navMode,r.planView&&(s.planView=r.planView),s.constrainVertical=r.constrainVertical,r.keyboardLayout?s.keyboardLayout=r.keyboardLayout:s.keyMap=r.keyMap,s.doublePickFlyTo=r.doublePickFlyTo,s.panRightClick=r.panRightClick,s.active=r.active,s.followPointer=r.followPointer,s.rotationInertia=r.rotationInertia,s.keyboardPanRate=r.keyboardPanRate,s.touchPanRate=r.touchPanRate,s.keyboardRotationRate=r.keyboardRotationRate,s.dragRotationRate=r.dragRotationRate,s.touchDollyRate=r.touchDollyRate,s.dollyInertia=r.dollyInertia,s.dollyProximityThreshold=r.dollyProximityThreshold,s.dollyMinSpeed=r.dollyMinSpeed,s.panInertia=r.panInertia,s.pointerEnabled=!0,s.keyboardDollyRate=r.keyboardDollyRate,s.mouseWheelDollyRate=r.mouseWheelDollyRate,s}return C(i,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",le.isString(e)){var t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{var s=e;this._keyMap=s}}},{key:"_isKeyDownForAction",value:function(e,t){var i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(var s=0,r=i.length;s0&&void 0!==arguments[0]?arguments[0]:{};this._controllers.pivotController.enablePivotSphere(e)}},{key:"disablePivotSphere",value:function(){this._controllers.pivotController.disablePivotSphere()}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),f(B(i.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var i=this.metaScene,s=e.properties;if(e.propertySets)for(var r=0,n=e.propertySets.length;r0?ep(t):null,o=i&&i.length>0?ep(i):null;return function e(t){if(t){var i=!0;(o&&o[t.type]||n&&!n[t.type])&&(i=!1),i&&s.push(t.id);var r=t.children;if(r)for(var a=0,l=r.length;a>t;i.sort(Qc);for(var a=new Int32Array(e.length),l=0,u=i.length;le[r+1]){var o=e[r];e[r]=e[r+1],e[r+1]=o}Vc=new Int32Array(e),t.sort(jc);for(var a=new Int32Array(e.length),l=0,u=t.length;l0)for(var s=i._meshes,r=0,n=s.length;r0)for(var o=this._meshes,a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._dtxEnabled=s.scene.dtxEnabled&&!1!==r.dtxEnabled,s._enableVertexWelding=!1,s._enableIndexBucketing=!1,s._vboBatchingLayerScratchMemory=io(),s._textureTranscoder=r.textureTranscoder||Tc(s.scene.viewer),s._maxGeometryBatchSize=r.maxGeometryBatchSize,s._aabb=$.collapseAABB3(),s._aabbDirty=!0,s._quantizationRanges={},s._vboInstancingLayers={},s._vboBatchingLayers={},s._dtxLayers={},s._meshList=[],s.layerList=[],s._entityList=[],s._geometries={},s._dtxBuckets={},s._textures={},s._textureSets={},s._transforms={},s._meshes={},s._unusedMeshes={},s._entities={},s.renderFlags=new jr,s.numGeometries=0,s.numPortions=0,s.numVisibleLayerPortions=0,s.numTransparentLayerPortions=0,s.numXRayedLayerPortions=0,s.numHighlightedLayerPortions=0,s.numSelectedLayerPortions=0,s.numEdgesLayerPortions=0,s.numPickableLayerPortions=0,s.numClippableLayerPortions=0,s.numCulledLayerPortions=0,s.numEntities=0,s._numTriangles=0,s._numLines=0,s._numPoints=0,s._edgeThreshold=r.edgeThreshold||10,s._origin=$.vec3(r.origin||[0,0,0]),s._position=$.vec3(r.position||[0,0,0]),s._rotation=$.vec3(r.rotation||[0,0,0]),s._quaternion=$.vec4(r.quaternion||[0,0,0,1]),s._conjugateQuaternion=$.vec4(r.quaternion||[0,0,0,1]),r.rotation&&$.eulerToQuaternion(s._rotation,"XYZ",s._quaternion),s._scale=$.vec3(r.scale||[1,1,1]),s._worldRotationMatrix=$.mat4(),s._worldRotationMatrixConjugate=$.mat4(),s._matrix=$.mat4(),s._matrixDirty=!0,s._rebuildMatrices(),s._worldNormalMatrix=$.mat4(),$.inverseMat4(s._matrix,s._worldNormalMatrix),$.transposeMat4(s._worldNormalMatrix),(r.matrix||r.position||r.rotation||r.scale||r.quaternion)&&(s._viewMatrix=$.mat4(),s._viewNormalMatrix=$.mat4(),s._viewMatrixDirty=!0,s._matrixNonIdentity=!0),s._opacity=1,s._colorize=[1,1,1],s._saoEnabled=!1!==r.saoEnabled,s._pbrEnabled=!1!==r.pbrEnabled,s._colorTextureEnabled=!1!==r.colorTextureEnabled,s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s._onCameraViewMatrix=s.scene.camera.on("matrix",(function(){s._viewMatrixDirty=!0})),s._meshesWithDirtyMatrices=[],s._numMeshesWithDirtyMatrices=0,s._onTick=s.scene.on("tick",(function(){for(;s._numMeshesWithDirtyMatrices>0;)s._meshesWithDirtyMatrices[--s._numMeshesWithDirtyMatrices]._updateMatrix()})),s._createDefaultTextureSet(),s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.colorize=r.colorize,s.opacity=r.opacity,s.backfaces=r.backfaces,s}return C(i,[{key:"_meshMatrixDirty",value:function(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}},{key:"_createDefaultTextureSet",value:function(){var e=new xc({id:"defaultColorTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new xc({id:"defaultMetalRoughTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new xc({id:"defaultNormalsTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new xc({id:"defaultEmissiveTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new xc({id:"defaultOcclusionTexture",texture:new Fn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Bc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"transforms",get:function(){return this._transforms}},{key:"textures",get:function(){return this._textures}},{key:"textureSets",get:function(){return this._textureSets}},{key:"meshes",get:function(){return this._meshes}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){}},{key:"matrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix},set:function(e){this._matrix.set(e||oh),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotationMatrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}},{key:"_rebuildMatrices",value:function(){this._matrixDirty&&($.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}},{key:"rotationMatrixConjugate",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}},{key:"_setWorldMatrixDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}},{key:"_sceneModelDirty",value:function(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(var e=0,t=this._entityList.length;e0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var l=e.colors,u=new Uint8Array(l.length),A=0,c=l.length;A>24&255,r=i>>16&255,n=i>>8&255,o=255&i;switch(e.pickColor=new Uint8Array([o,n,r,s]),e.solid="solid"===e.primitive,t.origin=$.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var i=0,s=e.buckets.length;i>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,n="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(s,".").concat(r),o=this._vboInstancingLayers[n];if(o)return o;for(var a=e.textureSet,l=e.geometry;!o;)switch(l.primitive){case"triangles":case"surface":o=new tl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":o=new tl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":o=new Ql({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":o=new Su({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[n]=o,this.layerList.push(o),o}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=$.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=$.createUUID()),void 0!==e.meshIds){var t=0;this._visible&&!1!==e.visible&&(t|=Ne),this._pickable&&!1!==e.pickable&&(t|=He),this._culled&&!1!==e.culled&&(t|=Qe),this._clippable&&!1!==e.clippable&&(t|=Ve),this._collidable&&!1!==e.collidable&&(t|=je),this._edges&&!1!==e.edges&&(t|=We),this._xrayed&&!1!==e.xrayed&&(t|=Ge),this._highlighted&&!1!==e.highlighted&&(t|=ze),this._selected&&!1!==e.selected&&(t|=Ke),e.flags=t,this._createEntity(e)}else this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],i=0,s=e.meshIds.length;it.sortId?1:0}));for(var o=0,a=this.layerList.length;o0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,i=this.layerList.length;t0){var t="".concat(this.id,"-dummyEntityForUnusedMeshes");this.warn('Creating dummy SceneModelEntity "'.concat(t,'" for unused SceneMeshes: [').concat(e.join(","),"]")),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(var n=0;n0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var i=this.scene.selectedMaterial._state;i.fill&&(i.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var s=this.scene.highlightMaterial._state;s.fill&&(s.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),s.edges&&(s.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e){for(var t=this.renderFlags,i=0,s=t.visibleLayers.length;i2&&void 0!==arguments[2]&&arguments[2],s=e.positionsCompressed||[],r=Hc(e.indices||[],t),n=Gc(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function s(i,s){return i!==e?e-i:s!==t?t-s:0}for(var r=0,o=(n.length>>1)-1;r<=o;){var a=o+r>>1,l=s(n[2*a],n[2*a+1]);if(l>0)r=a+1;else{if(!(l<0))return a;o=a-1}}return-r-1}var a=new Int32Array(n.length/2);a.fill(0);var l=s.length/3;if(l>8*(1<h.maxNumPositions&&(h=c()),h.bucketNumber>8)return[e];-1===u[v]&&(u[v]=h.numPositions++,h.positionsCompressed.push(s[3*v]),h.positionsCompressed.push(s[3*v+1]),h.positionsCompressed.push(s[3*v+2])),-1===u[g]&&(u[g]=h.numPositions++,h.positionsCompressed.push(s[3*g]),h.positionsCompressed.push(s[3*g+1]),h.positionsCompressed.push(s[3*g+2])),-1===u[m]&&(u[m]=h.numPositions++,h.positionsCompressed.push(s[3*m]),h.positionsCompressed.push(s[3*m+1]),h.positionsCompressed.push(s[3*m+2])),h.indices.push(u[v]),h.indices.push(u[g]),h.indices.push(u[m]);var _=void 0;(_=o(v,g))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(v,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(g,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]]))}var y=t/8*2,b=t/8,B=2*s.length+(r.length+n.length)*y,x=0;return s.length,A.forEach((function(e){x+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*b,e.positionsCompressed.length})),x>B?[e]:(i&&zc(A,e),A)}({positionsCompressed:s,indices:r,edgeIndices:n},s.length/3>65536?16:8):o=[{positionsCompressed:s,indices:r,edgeIndices:n}];return o}var Ah=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e,r))._positions=r.positions||[],r.indices)s._indices=r.indices;else{s._indices=[];for(var n=0,o=s._positions.length/3-1;n1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"BCFViewpoints",e,r)).originatingSystem=r.originatingSystem||"xeokit.io",s.authoringTool=r.authoringTool||"xeokit.io",s}return C(i,[{key:"getViewpoint",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=this.viewer.scene,s=i.camera,r=i.realWorldOffset,n=!0===t.reverseClippingPlanes,o={},a=$.normalizeVec3($.subVec3(s.look,s.eye,$.vec3())),l=s.eye,u=s.up;s.yUp&&(a=mh(a),l=mh(l),u=mh(u));var A=vh($.addVec3(l,r));"ortho"===s.projection?o.orthogonal_camera={camera_view_point:A,camera_direction:vh(a),camera_up_vector:vh(u),view_to_world_scale:s.ortho.scale}:o.perspective_camera={camera_view_point:A,camera_direction:vh(a),camera_up_vector:vh(u),field_of_view:s.perspective.fov};var c=i.sectionPlanes;for(var d in c)if(c.hasOwnProperty(d)){var p=c[d];if(!p.active)continue;var f=p.pos,v=void 0;v=n?$.negateVec3(p.dir,$.vec3()):p.dir,s.yUp&&(f=mh(f),v=mh(v)),$.addVec3(f,r),f=vh(f),v=vh(v),o.clipping_planes||(o.clipping_planes=[]),o.clipping_planes.push({location:f,direction:v})}var g=i.lineSets;for(var m in g)if(g.hasOwnProperty(m)){var _=g[m];o.lines||(o.lines=[]);for(var y=_.positions,b=_.indices,B=0,x=b.length/2;B1&&void 0!==arguments[1]?arguments[1]:{};if(e){var s=this.viewer,r=s.scene,n=r.camera,o=!1!==i.rayCast,a=!1!==i.immediate,l=!1!==i.reset,u=r.realWorldOffset,A=!0===i.reverseClippingPlanes;if(r.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.length>0&&e.clipping_planes.forEach((function(e){var t=gh(e.location,ch),i=gh(e.direction,ch);A&&$.negateVec3(i),$.subVec3(t,u),n.yUp&&(t=_h(t),i=_h(i)),new ln(r,{pos:t,dir:i})})),r.clearLines(),e.lines&&e.lines.length>0){var c=[],h=[],d=0;e.lines.forEach((function(e){e.start_point&&e.end_point&&(c.push(e.start_point.x),c.push(e.start_point.y),c.push(e.start_point.z),c.push(e.end_point.x),c.push(e.end_point.y),c.push(e.end_point.z),h.push(d++),h.push(d++))})),new Ah(r,{positions:c,indices:h,clippable:!1,collidable:!0})}if(r.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){var t=e.bitmap_type||"jpg",i=e.bitmap_data,s=gh(e.location,hh),o=gh(e.normal,dh),a=gh(e.up,ph),l=e.height||1;t&&i&&s&&o&&a&&(n.yUp&&(s=_h(s),o=_h(o),a=_h(a)),new Jn(r,{src:i,type:t,pos:s,normal:o,up:a,clippable:!1,collidable:!0,height:l}))})),l&&(r.setObjectsXRayed(r.xrayedObjectIds,!1),r.setObjectsHighlighted(r.highlightedObjectIds,!1),r.setObjectsSelected(r.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(r.setObjectsVisible(r.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!1}))}))):(r.setObjectsVisible(r.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!0}))})));var p=e.components.visibility.view_setup_hints;p&&(!1===p.spaces_visible&&r.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!0),void 0!==p.spaces_translucent&&r.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),p.space_boundaries_visible,!1===p.openings_visible&&r.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),p.space_boundaries_translucent,void 0!==p.openings_translucent&&r.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(r.setObjectsSelected(r.selectedObjectIds,!1),e.components.selection.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.selected=!0}))}))),e.components.translucency&&(r.setObjectsXRayed(r.xrayedObjectIds,!1),e.components.translucency.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.xrayed=!0}))}))),e.components.coloring&&e.components.coloring.forEach((function(e){var s=e.color,r=0,n=!1;8===s.length&&((r=parseInt(s.substring(0,2),16)/256)<=1&&r>=.95&&(r=1),s=s.substring(2),n=!0);var o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((function(e){return t._withBCFComponent(i,e,(function(e){e.colorize=o,n&&(e.opacity=r)}))}))}))}if(e.perspective_camera||e.orthogonal_camera){var f,v,g,m;if(e.perspective_camera?(f=gh(e.perspective_camera.camera_view_point,ch),v=gh(e.perspective_camera.camera_direction,ch),g=gh(e.perspective_camera.camera_up_vector,ch),n.perspective.fov=e.perspective_camera.field_of_view,m="perspective"):(f=gh(e.orthogonal_camera.camera_view_point,ch),v=gh(e.orthogonal_camera.camera_direction,ch),g=gh(e.orthogonal_camera.camera_up_vector,ch),n.ortho.scale=e.orthogonal_camera.view_to_world_scale,m="ortho"),$.subVec3(f,u),n.yUp&&(f=_h(f),v=_h(v),g=_h(g)),o){var _=r.pick({pickSurface:!0,origin:f,direction:v});v=_?_.worldPos:$.addVec3(f,v,ch)}else v=$.addVec3(f,v,ch);a?(n.eye=f,n.look=v,n.up=g,n.projection=m):s.cameraFlight.flyTo({eye:f,look:v,up:g,duration:i.duration,projection:m})}}}},{key:"_withBCFComponent",value:function(e,t,i){var s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){var n=t.authoring_tool_id,o=r.objects[n];if(o)return void i(o);if(e.updateCompositeObjects)if(s.metaScene.metaObjects[n])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}if(t.ifc_guid){var a=t.ifc_guid,l=r.objects[a];if(l)return void i(l);if(e.updateCompositeObjects)if(s.metaScene.metaObjects[a])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(a),i);Object.keys(r.models).forEach((function(t){var n=$.globalizeObjectId(t,a),o=r.objects[n];o?i(o):e.updateCompositeObjects&&s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}))}}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this)}}]),i}();function vh(e){return{x:e[0],y:e[1],z:e[2]}}function gh(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function mh(e){return new Float64Array([e[0],-e[2],e[1]])}function _h(e){return new Float64Array([e[0],e[2],-e[1]])}function yh(e){var t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0")}var bh=$.vec3(),Bh=function(e,t,i,s){var r=e-i,n=t-s;return Math.sqrt(r*r+n*n)},xh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(w(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._eventSubs={};var n=s.plugin.viewer.scene;s._originMarker=new $e(n,r.origin),s._targetMarker=new $e(n,r.target),s._originWorld=$.vec3(),s._targetWorld=$.vec3(),s._wp=new Float64Array(24),s._vp=new Float64Array(24),s._pp=new Float64Array(24),s._cp=new Float64Array(8),s._xAxisLabelCulled=!1,s._yAxisLabelCulled=!1,s._zAxisLabelCulled=!1,s._color=r.color||s.plugin.defaultColor;var o=r.onMouseOver?function(e){r.onMouseOver(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},u=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},c=r.onContextMenu?function(e){r.onContextMenu(e,b(s))}:null,h=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};return s._originDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._targetDot=new tt(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._lengthWire=new et(s._container,{color:s._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._xAxisWire=new et(s._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._yAxisWire=new et(s._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._zAxisWire=new et(s._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._lengthLabel=new it(s._container,{fillColor:s._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._xAxisLabel=new it(s._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._yAxisLabel=new it(s._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._zAxisLabel=new it(s._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._sectionPlanesDirty=!0,s._visible=!1,s._originVisible=!1,s._targetVisible=!1,s._wireVisible=!1,s._axisVisible=!1,s._xAxisVisible=!1,s._yAxisVisible=!1,s._zAxisVisible=!1,s._axisEnabled=!0,s._labelsVisible=!1,s._labelsOnWires=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s._onMetricsUnits=n.metrics.on("units",(function(){s._cpDirty=!0,s._needUpdate()})),s._onMetricsScale=n.metrics.on("scale",(function(){s._cpDirty=!0,s._needUpdate()})),s._onMetricsOrigin=n.metrics.on("origin",(function(){s._cpDirty=!0,s._needUpdate()})),s._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){s._sectionPlanesDirty=!0,s._needUpdate()})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.targetVisible=r.targetVisible,s.wireVisible=r.wireVisible,s.axisVisible=r.axisVisible,s.xAxisVisible=r.xAxisVisible,s.yAxisVisible=r.yAxisVisible,s.zAxisVisible=r.zAxisVisible,s.labelsVisible=r.labelsVisible,s.labelsOnWires=r.labelsOnWires,s}return C(i,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}var t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var s=this._pp,r=this._cp,n=e.canvas.canvas.getBoundingClientRect(),o=this._container.getBoundingClientRect(),a=n.top-o.top,l=n.left-o.left,u=e.canvas.boundary,A=u[2],c=u[3],h=0,d=this.plugin.viewer.scene.metrics,p=d.scale,f=d.units,v=d.unitsInfo[f].abbrev,g=0,m=s.length;g1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e.viewer.scene)).pointerLens=r.pointerLens,s._active=!1,s._currentDistanceMeasurement=null,s._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},s._initMarkerDiv(),s._onCameraControlHoverSnapOrSurface=null,s._onCameraControlHoverSnapOrSurfaceOff=null,s._onMouseDown=null,s._onMouseUp=null,s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s._snapping=!1!==r.snapping,s._mouseState=0,s._attachPlugin(e,r),s}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this._markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.distanceMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this._markerDiv||this._initMarkerDiv(),this.fire("activated",!0);var t=this.distanceMeasurementsPlugin,i=this.scene,s=t.viewer.cameraControl,r=i.canvas.canvas;i.input;var n,o,a=!1,l=$.vec3(),u=$.vec2(),A=null;this._mouseState=0;var c=function e(t){return t.offsetTop+(t.offsetParent&&e(t.offsetParent))},h=function e(t){return t.offsetLeft+(t.offsetParent&&e(t.offsetParent))};this._onCameraControlHoverSnapOrSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){var i=t.snappedCanvasPos||t.canvasPos;a=!0,l.set(t.worldPos),u.set(t.canvasPos),0===e._mouseState?(e._markerDiv.style.left="".concat(h(r)+i[0]-5,"px"),e._markerDiv.style.top="".concat(c(r)+i[1]-5,"px"),e._markerDiv.style.background="pink",t.snappedToVertex||t.snappedToEdge?(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,e.pointerLens.snapped=!0),e._markerDiv.style.background="greenyellow",e._markerDiv.style.border="2px solid green"):(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.canvasPos,e.pointerLens.snapped=!1),e._markerDiv.style.background="pink",e._markerDiv.style.border="2px solid red"),A=t.entity):(e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px"),r.style.cursor="pointer",e._currentDistanceMeasurement&&(e._currentDistanceMeasurement.wireVisible=e._currentDistanceMeasurementInitState.wireVisible,e._currentDistanceMeasurement.axisVisible=e._currentDistanceMeasurementInitState.axisVisible&&e.distanceMeasurementsPlugin.defaultAxisVisible,e._currentDistanceMeasurement.xAxisVisible=e._currentDistanceMeasurementInitState.xAxisVisible&&e.distanceMeasurementsPlugin.defaultXAxisVisible,e._currentDistanceMeasurement.yAxisVisible=e._currentDistanceMeasurementInitState.yAxisVisible&&e.distanceMeasurementsPlugin.defaultYAxisVisible,e._currentDistanceMeasurement.zAxisVisible=e._currentDistanceMeasurementInitState.zAxisVisible&&e.distanceMeasurementsPlugin.defaultZAxisVisible,e._currentDistanceMeasurement.targetVisible=e._currentDistanceMeasurementInitState.targetVisible,e._currentDistanceMeasurement.target.worldPos=l.slice(),e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px")})),r.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(n=e.clientX,o=e.clientY)}),r.addEventListener("mouseup",this._onMouseUp=function(i){1===i.which&&(i.clientX>n+20||i.clientXo+20||i.clientY1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,"DistanceMeasurements",e))._pointerLens=r.pointerLens,s._container=r.container||document.body,s._defaultControl=null,s._measurements={},s.labelMinAxisLength=r.labelMinAxisLength,s.defaultVisible=!1!==r.defaultVisible,s.defaultOriginVisible=!1!==r.defaultOriginVisible,s.defaultTargetVisible=!1!==r.defaultTargetVisible,s.defaultWireVisible=!1!==r.defaultWireVisible,s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.defaultAxisVisible=!1!==r.defaultAxisVisible,s.defaultXAxisVisible=!1!==r.defaultXAxisVisible,s.defaultYAxisVisible=!1!==r.defaultYAxisVisible,s.defaultZAxisVisible=!1!==r.defaultZAxisVisible,s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.zIndex=r.zIndex||1e4,s.defaultLabelsOnWires=!1!==r.defaultLabelsOnWires,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"pointerLens",get:function(){return this._pointerLens}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new Ph(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"labelMinAxisLength",get:function(){return this._labelMinAxisLength},set:function(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,s=t.target,r=new xh(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:t.visible,wireVisible:t.wireVisible,axisVisible:!1!==t.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==t.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==t.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisible:!1!==t.zAxisVisible&&!1!==this.defaultZAxisVisible,labelsVisible:!1!==t.labelsVisible&&!1!==this.defaultLabelsVisible,originVisible:t.originVisible,targetVisible:t.targetVisible,color:t.color,labelsOnWires:!1!==t.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(function(){delete e._measurements[r.id]})),this.fire("measurementCreated",r),r}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,"FastNav",e))._hideColorTexture=!1!==r.hideColorTexture,s._hidePBR=!1!==r.hidePBR,s._hideSAO=!1!==r.hideSAO,s._hideEdges=!1!==r.hideEdges,s._hideTransparentObjects=!!r.hideTransparentObjects,s._scaleCanvasResolution=!!r.scaleCanvasResolution,s._scaleCanvasResolutionFactor=r.scaleCanvasResolutionFactor||.6,s._delayBeforeRestore=!1!==r.delayBeforeRestore,s._delayBeforeRestoreSeconds=r.delayBeforeRestoreSeconds||.5;var n=1e3*s._delayBeforeRestoreSeconds,o=!1,a=function(){n=1e3*s._delayBeforeRestoreSeconds,o||(e.scene._renderer.setColorTextureEnabled(!s._hideColorTexture),e.scene._renderer.setPBREnabled(!s._hidePBR),e.scene._renderer.setSAOEnabled(!s._hideSAO),e.scene._renderer.setTransparentEnabled(!s._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!s._hideEdges),s._scaleCanvasResolution?e.scene.canvas.resolutionScale=s._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=1,o=!0)},l=function(){e.scene.canvas.resolutionScale=1,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),o=!1};s._onCanvasBoundary=e.scene.canvas.on("boundary",a),s._onCameraMatrix=e.scene.camera.on("matrix",a),s._onSceneTick=e.scene.on("tick",(function(e){o&&(n-=e.deltaTime,(!s._delayBeforeRestore||n<=0)&&l())}));var u=!1;return s._onSceneMouseDown=e.scene.input.on("mousedown",(function(){u=!0})),s._onSceneMouseUp=e.scene.input.on("mouseup",(function(){u=!1})),s._onSceneMouseMove=e.scene.input.on("mousemove",(function(){u&&a()})),s}return C(i,[{key:"hideColorTexture",get:function(){return this._hideColorTexture},set:function(e){this._hideColorTexture=e}},{key:"hidePBR",get:function(){return this._hidePBR},set:function(e){this._hidePBR=e}},{key:"hideSAO",get:function(){return this._hideSAO},set:function(e){this._hideSAO=e}},{key:"hideEdges",get:function(){return this._hideEdges},set:function(e){this._hideEdges=e}},{key:"hideTransparentObjects",get:function(){return this._hideTransparentObjects},set:function(e){this._hideTransparentObjects=!1!==e}},{key:"scaleCanvasResolution",get:function(){return this._scaleCanvasResolution},set:function(e){this._scaleCanvasResolution=e}},{key:"scaleCanvasResolutionFactor",get:function(){return this._scaleCanvasResolutionFactor},set:function(e){this._scaleCanvasResolutionFactor=e||.6}},{key:"delayBeforeRestore",get:function(){return this._delayBeforeRestore},set:function(e){this._delayBeforeRestore=e}},{key:"delayBeforeRestoreSeconds",get:function(){return this._delayBeforeRestoreSeconds},set:function(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),f(B(i.prototype),"destroy",this).call(this)}}]),i}(),Fh=function(){function e(){w(this,e)}return C(e,[{key:"getMetaModel",value:function(e,t,i){le.loadJSON(e,(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLTF",value:function(e,t,i){le.loadArraybuffer(e,(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLB",value:function(e,t,i){le.loadArraybuffer(e,(function(e){t(e)}),(function(e){i(e)}))}},{key:"getArrayBuffer",value:function(e,t,i,s){!function(e,t,i,s){var r=function(){};i=i||r,s=s||r;var n=/^data:(.*?)(;base64)?,(.*)$/,o=t.match(n);if(o){var a=!!o[2],l=o[3];l=window.decodeURIComponent(l),a&&(l=window.atob(l));try{for(var u=new ArrayBuffer(l.length),A=new Uint8Array(u),c=0;c0&&void 0!==arguments[0]?arguments[0]:{};w(this,e),this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=t.messages,this.locale=t.locale}return C(e,[{key:"messages",set:function(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}},{key:"loadMessages",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e)this._messages[t]=e[t];this.messages=this._messages}},{key:"clearMessages",value:function(){this.messages={}}},{key:"locales",get:function(){return this._locales}},{key:"locale",get:function(){return this._locale},set:function(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}},{key:"translate",value:function(e,t){var i=this._messages[this._locale];if(!i)return null;var s=kh(e,i);return s?t?Ih(s,t):s:null}},{key:"translatePlurals",value:function(e,t,i){var s=this._messages[this._locale];if(!s)return null;var r=kh(e,s);return(r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one)?(r=Ih(r,[t]),i&&(r=Ih(r,i)),r):null}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);var s=this._eventSubs[e];if(s)for(var r in s){if(s.hasOwnProperty(r))s[r].callback(t)}}},{key:"on",value:function(e,t){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new Q),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});var i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);var s=this._eventSubIDMap.addItem();i[s]={callback:t},this._eventSubEvents[s]=e;var r=this._events[e];return void 0!==r&&t(r),s}},{key:"off",value:function(e){if(null!=e&&this._eventSubEvents){var t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];var i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}}]),e}();function kh(e,t){if(t[e])return t[e];for(var i=e.split("."),s=t,r=0,n=i.length;s&&r1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}var Dh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).t=r.t,s}return C(i,[{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"tangent",get:function(){return this.getTangent(this._t)}},{key:"length",get:function(){var e=this._getLengths();return e[e.length-1]}},{key:"getTangent",value:function(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),n=this.getPoint(s),o=$.subVec3(n,r,[]);return $.normalizeVec3(o,[])}},{key:"getPointAt",value:function(e){var t=this.getUToTMapping(e);return this.getPoint(t)}},{key:"getPoints",value:function(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}},{key:"_getLengths",value:function(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),n=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),n+=$.lenVec3($.subVec3(t,r,[])),s.push(n),r=t;return this.cacheArcLengths=s,s}},{key:"_updateArcLengths",value:function(){this.needsUpdate=!0,this._getLengths()}},{key:"getUToTMapping",value:function(e,t){var i,s=this._getLengths(),r=0,n=s.length;i=t||e*s[n-1];for(var o,a=0,l=n-1;a<=l;)if((o=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(o>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(n-1);var u=s[r];return(r+(i-u)/(s[r+1]-u))/(n-1)}}]),i}(),Sh=function(e){g(i,Dh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).points=r.points,s.t=r.t,s}return C(i,[{key:"points",get:function(){return this._points},set:function(e){this._points=e||[]}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,n=t[0===s?s:s-1],o=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],u=$.vec3();return u[0]=$.catmullRomInterpolate(n[0],o[0],a[0],l[0],r),u[1]=$.catmullRomInterpolate(n[1],o[1],a[1],l[1],r),u[2]=$.catmullRomInterpolate(n[2],o[2],a[2],l[2],r),u}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}},{key:"getJSON",value:function(){return{points:points,t:this._t}}}]),i}(),Th=$.vec3(),Rh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._frames=[],s._eyeCurve=new Sh(b(s)),s._lookCurve=new Sh(b(s)),s._upCurve=new Sh(b(s)),r.frames&&(s.addFrames(r.frames),s.smoothFrameTimes(1)),s}return C(i,[{key:"type",get:function(){return"CameraPath"}},{key:"frames",get:function(){return this._frames}},{key:"eyeCurve",get:function(){return this._eyeCurve}},{key:"lookCurve",get:function(){return this._lookCurve}},{key:"upCurve",get:function(){return this._upCurve}},{key:"saveFrame",value:function(e){var t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}},{key:"addFrame",value:function(e,t,i,s){var r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}},{key:"addFrames",value:function(e){for(var t,i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Th),t.look=this._lookCurve.getPoint(e,Th),t.up=this._upCurve.getPoint(e,Th)}},{key:"sampleFrame",value:function(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}},{key:"smoothFrameTimes",value:function(e){if(0!==this._frames.length){var t=$.vec3(),i=0;this._frames[0].t=0;for(var s=[],r=1,n=this._frames.length;r1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._look1=$.vec3(),s._eye1=$.vec3(),s._up1=$.vec3(),s._look2=$.vec3(),s._eye2=$.vec3(),s._up2=$.vec3(),s._orthoScale1=1,s._orthoScale2=1,s._flying=!1,s._flyEyeLookUp=!1,s._flyingEye=!1,s._flyingLook=!1,s._callback=null,s._callbackScope=null,s._time1=null,s._time2=null,s.easing=!1!==r.easing,s.duration=r.duration,s.fit=r.fit,s.fitFOV=r.fitFOV,s.trail=r.trail,s}return C(i,[{key:"type",get:function(){return"CameraFlightAnimation"}},{key:"flyTo",value:function(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;var s,r,n,o,a,l=this.scene.camera,u=!!e.projection&&e.projection!==l.projection;if(this._eye1[0]=l.eye[0],this._eye1[1]=l.eye[1],this._eye1[2]=l.eye[2],this._look1[0]=l.look[0],this._look1[1]=l.look[1],this._look1[2]=l.look[2],this._up1[0]=l.up[0],this._up1[1]=l.up[1],this._up1[2]=l.up[2],this._orthoScale1=l.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye&&e.look||e.up)r=e.eye,n=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)n=e.look;else{var A=e;if((le.isNumeric(A)||le.isString(A))&&(a=A,!(A=this.scene.components[a])))return this.error("Component not found: "+le.inQuotes(a)),void(t&&(i?t.call(i):t()));u||(s=A.aabb||this.scene.aabb)}var c=e.poi;if(s){if(s[3]=1;e>1&&(e=1);var s=this.easing?i._ease(e,0,1,1):e,r=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?($.subVec3(r.eye,r.look,Qh),r.eye=$.lerpVec3(s,0,1,this._eye1,this._eye2,Oh),r.look=$.subVec3(Oh,Qh,Uh)):this._flyingLook&&(r.look=$.lerpVec3(s,0,1,this._look1,this._look2,Uh),r.up=$.lerpVec3(s,0,1,this._up1,this._up2,Nh)):this._flyingEyeLookUp&&(r.eye=$.lerpVec3(s,0,1,this._eye1,this._eye2,Oh),r.look=$.lerpVec3(s,0,1,this._look1,this._look2,Uh),r.up=$.lerpVec3(s,0,1,this._up1,this._up2,Nh)),this._projection2){var n="ortho"===this._projection2?i._easeOutExpo(e,0,1,1):i._easeInCubic(e,0,1,1);r.customProjection.matrix=$.lerpMat4(n,0,1,this._projMatrix1,this._projMatrix2)}else r.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return r.ortho.scale=this._orthoScale2,void this.stop();_e.scheduleTask(this._update,this)}}},{key:"stop",value:function(){if(this._flying){this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);var e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}}},{key:"cancel",value:function(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}},{key:"duration",get:function(){return this._duration/1e3},set:function(e){this._duration=e?1e3*e:500,this.stop()}},{key:"fit",get:function(){return this._fit},set:function(e){this._fit=!1!==e}},{key:"fitFOV",get:function(){return this._fitFOV},set:function(e){this._fitFOV=e||45}},{key:"trail",get:function(){return this._trail},set:function(e){this._trail=!!e}},{key:"destroy",value:function(){this.stop(),f(B(i.prototype),"destroy",this).call(this)}}],[{key:"_ease",value:function(e,t,i,s){return-i*(e/=s)*(e-2)+t}},{key:"_easeInCubic",value:function(e,t,i,s){return i*(e/=s)*e*e+t}},{key:"_easeOutExpo",value:function(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}}]),i}(),Vh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._cameraFlightAnimation=new Hh(b(s)),s._t=0,s.state=i.SCRUBBING,s._playingFromT=0,s._playingToT=0,s._playingRate=r.playingRate||1,s._playingDir=1,s._lastTime=null,s.cameraPath=r.cameraPath,s._tick=s.scene.on("tick",s._updateT,b(s)),s}return C(i,[{key:"type",get:function(){return"CameraPathAnimation"}},{key:"_updateT",value:function(){var e=this._cameraPath;if(e){var t,s,r=performance.now(),n=this._lastTime?.001*(r-this._lastTime):0;if(this._lastTime=r,0!==n)switch(this.state){case i.SCRUBBING:return;case i.PLAYING:if(this._t+=this._playingRate*n,0===(t=this._cameraPath.frames.length)||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=i.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case i.PLAYING_TO:s=this._t+this._playingRate*n*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=i.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}}},{key:"_ease",value:function(e,t,i,s){return-i*(e/=s)*(e-2)+t}},{key:"cameraPath",get:function(){return this._cameraPath},set:function(e){this._cameraPath=e}},{key:"rate",get:function(){return this._playingRate},set:function(e){this._playingRate=e}},{key:"play",value:function(){this._cameraPath&&(this._lastTime=null,this.state=i.PLAYING)}},{key:"playToT",value:function(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=i.PLAYING_TO)}},{key:"playToFrame",value:function(e){var t=this._cameraPath;if(t){var i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}}},{key:"flyToFrame",value:function(e,t){var s=this._cameraPath;if(s){var r=s.frames[e];r?(this.state=i.SCRUBBING,this._cameraFlightAnimation.flyTo(r,t)):this.error("flyToFrame - frame index out of range: "+e)}}},{key:"scrubToT",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=i.SCRUBBING))}},{key:"scrubToFrame",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(t.frames[e]?(t.loadFrame(this._t),this.state=i.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)))}},{key:"stop",value:function(){this.state=i.SCRUBBING,this.fire("stopped")}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene.off(this._tick)}}]),i}();Vh.STOPPED=0,Vh.SCRUBBING=1,Vh.PLAYING=2,Vh.PLAYING_TO=3;var jh=$.vec3(),Gh=$.vec3();$.vec3();var zh=$.vec3([0,-1,0]),Kh=$.vec4([0,0,0,1]),Wh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._src=null,s._image=null,s._pos=$.vec3(),s._origin=$.vec3(),s._rtcPos=$.vec3(),s._dir=$.vec3(),s._size=1,s._imageSize=$.vec2(),s._texture=new Tn(b(s)),s._plane=new en(b(s),{geometry:new Ii(b(s),zn({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Li(b(s),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:s._texture,emissiveMap:s._texture,backfaces:!0}),clippable:r.clippable}),s._grid=new en(b(s),{geometry:new Ii(b(s),Gn({size:1,divisions:10})),material:new Li(b(s),{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:r.clippable}),s._node=new mn(b(s),{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[s._plane,s._grid]}),s._gridVisible=!1,s.visible=!0,s.gridVisible=r.gridVisible,s.position=r.position,s.rotation=r.rotation,s.dir=r.dir,s.size=r.size,s.collidable=r.collidable,s.clippable=r.clippable,s.pickable=r.pickable,s.opacity=r.opacity,r.image?s.image=r.image:s.src=r.src,s}return C(i,[{key:"visible",get:function(){return this._plane.visible},set:function(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}},{key:"gridVisible",get:function(){return this._gridVisible},set:function(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"position",get:function(){return this._pos},set:function(e){this._pos.set(e||[0,0,0]),Re(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}},{key:"rotation",get:function(){return this._node.rotation},set:function(e){this._node.rotation=e}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"dir",get:function(){return this._dir},set:function(e){if(this._dir.set(e||[0,0,-1]),e){var t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];$.subVec3(t,this.position,jh);var s=-$.dotVec3(i,jh);$.normalizeVec3(i),$.mulVec3Scalar(i,s,Gh),$.vec3PairToQuaternion(zh,e,Kh),this._node.quaternion=Kh}}},{key:"collidable",get:function(){return this._node.collidable},set:function(e){this._node.collidable=!1!==e}},{key:"clippable",get:function(){return this._node.clippable},set:function(e){this._node.clippable=!1!==e}},{key:"pickable",get:function(){return this._node.pickable},set:function(e){this._node.pickable=!1!==e}},{key:"opacity",get:function(){return this._node.opacity},set:function(e){this._node.opacity=e}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this)}},{key:"_updatePlaneSizeFromImage",value:function(){var e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){var s=i/t;this._node.scale=[e,1,e*s]}else{var r=t/i;this._node.scale=[e*r,1,e]}}}]),i}(),Xh=function(e){g(i,gi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i);var n=b(s=t.call(this,e,r));s._shadowRenderBuf=null,s._shadowViewMatrix=null,s._shadowProjMatrix=null,s._shadowViewMatrixDirty=!0,s._shadowProjMatrixDirty=!0;var o=s.scene.camera,a=s.scene.canvas;return s._onCameraViewMatrix=o.on("viewMatrix",(function(){s._shadowViewMatrixDirty=!0})),s._onCameraProjMatrix=o.on("projMatrix",(function(){s._shadowProjMatrixDirty=!0})),s._onCanvasBoundary=a.on("boundary",(function(){s._shadowProjMatrixDirty=!0})),s._state=new Jt({type:"point",pos:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:r.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(n._shadowViewMatrixDirty){n._shadowViewMatrix||(n._shadowViewMatrix=$.identityMat4());var e=n._state.pos,t=o.look,i=o.up;$.lookAtMat4v(e,t,i,n._shadowViewMatrix),n._shadowViewMatrixDirty=!1}return n._shadowViewMatrix},getShadowProjMatrix:function(){if(n._shadowProjMatrixDirty){n._shadowProjMatrix||(n._shadowProjMatrix=$.identityMat4());var e=n.scene.canvas.canvas;$.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,n._shadowProjMatrix),n._shadowProjMatrixDirty=!1}return n._shadowProjMatrix},getShadowRenderBuf:function(){return n._shadowRenderBuf||(n._shadowRenderBuf=new jt(n.scene.canvas.canvas,n.scene.canvas.gl,{size:[1024,1024]})),n._shadowRenderBuf}}),s.pos=r.pos,s.color=r.color,s.intensity=r.intensity,s.constantAttenuation=r.constantAttenuation,s.linearAttenuation=r.linearAttenuation,s.quadraticAttenuation=r.quadraticAttenuation,s.castsShadow=r.castsShadow,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"PointLight"}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"constantAttenuation",get:function(){return this._state.attenuation[0]},set:function(e){this._state.attenuation[0]=e||0,this.glRedraw()}},{key:"linearAttenuation",get:function(){return this._state.attenuation[1]},set:function(e){this._state.attenuation[1]=e||0,this.glRedraw()}},{key:"quadraticAttenuation",get:function(){return this._state.attenuation[2]},set:function(e){this._state.attenuation[2]=e||0,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(B(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}();function Jh(e){return 0==(e&e-1)}function Yh(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var Zh=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,i);var n=(s=t.call(this,e,r)).scene.canvas.gl;return s._state=new Jt({texture:new Fn({gl:n,target:n.TEXTURE_CUBE_MAP}),flipY:s._checkFlipY(r.minFilter),encoding:s._checkEncoding(r.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),s._src=r.src,s._images=[],s._loadSrc(r.src),se.memory.textures++,s}return C(i,[{key:"type",get:function(){return"CubeTexture"}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}},{key:"_loadSrc",value:function(e){var t=this,i=this.scene.canvas.gl;this._images=[];for(var s=!1,r=0,n=function(n){var o,a,l=new Image;l.onload=(o=l,a=n,function(){if(!s&&(o=function(e){if(!Jh(e.width)||!Jh(e.height)){var t=document.createElement("canvas");t.width=Yh(e.width),t.height=Yh(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}(o),t._images[a]=o,6==++r)){var e=t._state.texture;e||(e=new Fn({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}),l.onerror=function(){s=!0},l.src=e[n]},o=0;o1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).scene._lightsState.addReflectionMap(s._state),s.scene._reflectionMapCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"ReflectionMap"}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._reflectionMapDestroyed(this)}}]),i}(),$h=function(e){g(i,Zh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).scene._lightMapCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"LightMap"}},{key:"destroy",value:function(){f(B(i.prototype),"destroy",this).call(this),this.scene._lightMapDestroyed(this)}}]),i}(),ed=function(e){g(i,$e);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,{entity:r.entity,occludable:r.occludable,worldPos:r.worldPos}))._occluded=!1,s._visible=!0,s._src=null,s._image=null,s._pos=$.vec3(),s._origin=$.vec3(),s._rtcPos=$.vec3(),s._dir=$.vec3(),s._size=1,s._imageSize=$.vec2(),s._texture=new Tn(b(s),{src:r.src}),s._geometry=new Ii(b(s),{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),s._mesh=new en(b(s),{geometry:s._geometry,material:new Li(b(s),{ambient:[.9,.3,.9],shininess:30,diffuseMap:s._texture,backfaces:!0}),scale:[1,1,1],position:r.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),s.visible=!0,s.collidable=r.collidable,s.clippable=r.clippable,s.pickable=r.pickable,s.opacity=r.opacity,s.size=r.size,r.image?s.image=r.image:s.src=r.src,s}return C(i,[{key:"_setVisible",value:function(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,f(B(i.prototype),"_setVisible",this).call(this,e)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"collidable",get:function(){return this._mesh.collidable},set:function(e){this._mesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._mesh.clippable},set:function(e){this._mesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._mesh.pickable},set:function(e){this._mesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._mesh.opacity},set:function(e){this._mesh.opacity=e}},{key:"_updatePlaneSizeFromImage",value:function(){var e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}]),i}(),td=function(){function e(t){w(this,e),this._eye=$.vec3(),this._look=$.vec3(),this._up=$.vec3(),this._projection={},t&&this.saveCamera(t)}return C(e,[{key:"saveCamera",value:function(e){var t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}},{key:"restoreCamera",value:function(e,t){var i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(function(){r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}]),e}(),id=$.vec3(),sd=function(){function e(t){if(w(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,t){var i=t.metaScene.scene;this.saveObjects(i,t)}}return C(e,[{key:"saveObjects",value:function(e,t,i){this.numObjects=0,this._mask=i?le.apply(i,{}):null;for(var s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,A=!i||i.colorize,c=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).v0=r.v0,s.v1=r.v1,s.v2=r.v2,s.v3=r.v3,s.t=r.t,s}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"v3",get:function(){return this._v3},set:function(e){this.fire("v3",this._v3=e||$.vec3([0,0,0]))}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=$.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=$.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}]),i}(),ad=function(e){g(i,Dh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._cachedLengths=[],s._dirty=!0,s._curves=[],s._t=0,s._dirtySubs=[],s._destroyedSubs=[],s.curves=r.curves||[],s.t=r.t,s}return C(i,[{key:"addCurve",value:function(e){this._curves.push(e),this._dirty=!0}},{key:"curves",get:function(){return this._curves},set:function(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"length",get:function(){var e=this._getCurveLengths();return e[e.length-1]}},{key:"getPoint",value:function(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var n=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(n)}r++}return null}},{key:"_getCurveLengths",value:function(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r)).v0=r.v0,s.v1=r.v1,s.v2=r.v2,s.t=r.t,s}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=$.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=$.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}]),i}(),ud=function(e){g(i,lh);var t=_(i);function i(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),t.call(this,e,s)}return C(i)}(),Ad=function(e){g(i,Be);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,i),(s=t.call(this,e,r))._skyboxMesh=new en(b(s),{geometry:new Ii(b(s),{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Li(b(s),{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Tn(b(s),{src:r.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:r.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),s.size=r.size,s.active=r.active,s}return C(i,[{key:"size",get:function(){return this._size},set:function(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}},{key:"active",get:function(){return this._skyboxMesh.visible},set:function(e){this._skyboxMesh.visible=e}}]),i}(),cd=function(){function e(){w(this,e)}return C(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),hd=$.vec4(),dd=$.vec4(),pd=$.vec3(),fd=$.vec3(),vd=$.vec3(),gd=$.vec4(),md=$.vec4(),_d=$.vec4(),yd=function(){function e(t){w(this,e),this._scene=t}return C(e,[{key:"dollyToCanvasPos",value:function(e,t,i){var s=!1,r=this._scene.camera;if(e){var n=$.subVec3(e,r.eye,pd);s=$.lenVec3(n)0&&void 0!==arguments[0]?arguments[0]:{};this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);var t=e.color||[1,0,0];this._pivotSphereMaterial=new Li(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}},{key:"disablePivotSphere",value:function(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}},{key:"startPivot",value:function(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;var e=this._scene.camera,t=$.lookAtMat4v(e.eye,e.look,e.worldUp);$.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var i=this.getPivotPos();this._cameraOffset[2]+=$.distVec3(e.eye,i),t=$.inverseMat4(t);var s=$.transformVec3(t,this._cameraOffset),r=$.vec3();if($.subVec3(e.eye,i,r),$.addVec3(r,s),e.zUp){var n=r[1];r[1]=r[2],r[2]=n}this._radius=$.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=$.normalizeVec3($.subVec3(e.look,e.eye,bd)),i=$.cross3Vec3(t,e.worldUp,Bd);return $.sqLenVec3(i)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,i=Math.abs($.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),o=[0,0,-1,1],a=$.dotVec4(o,r)/$.dotVec4(o,n),l=wd;t.project.unproject(e,a,Pd,Cd,l);var u=$.normalizeVec3($.subVec3(l,t.eye,bd)),A=$.addVec3(t.eye,$.mulVec3Scalar(u,i,Bd),xd);this.setPivotPos(A)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var i=this._scene.camera,s=-e,r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=$.clamp(this._polar,.001,Math.PI-.001);var n=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){var o=n[1];n[1]=n[2],n[2]=o}var a=$.lenVec3($.subVec3(i.look,i.eye,$.vec3())),l=this.getPivotPos();$.addVec3(n,l);var u=$.lookAtMat4v(n,l,i.worldUp);u=$.inverseMat4(u);var A=$.transformVec3(u,this._cameraOffset);u[12]-=A[0],u[13]-=A[1],u[14]-=A[2];var c=[u[8],u[9],u[10]];i.eye=[u[12],u[13],u[14]],$.subVec3(i.eye,$.mulVec3Scalar(c,a),i.look),i.up=[u[4],u[5],u[6]],this.showPivot()}}},{key:"showPivot",value:function(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}},{key:"hidePivot",value:function(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),Fd=function(){function e(t,i){w(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=i,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=$.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}return C(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){var e="".concat(~~this.pickCursorPos[0],"-").concat(~~this.pickCursorPos[1],"-").concat(this.scheduleSnapOrPick,"-").concat(this.schedulePickSurface,"-").concat(this.schedulePickEntity);if(this._lastHash!==e){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;var t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var i=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});i&&(i.snappedToEdge||i.snappedToVertex)?(this.snapPickResult=i,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var s=this.pickResult.canvasPos;if(s[0]===this.pickCursorPos[0]&&s[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var r=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}}},{key:"fireEvents",value:function(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new bt;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}]),e}(),Ed=$.vec2(),kd=function(){function e(t,i,s,r,n){w(this,e),this._scene=t;var o,a,l,u=i.pickController,A=0,c=0,h=0,d=0,p=!1,f=$.vec3(),v=!0,g=this._scene.canvas.canvas,m=[];function _(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];g.style.cursor="move",y(),e&&b()}function y(){A=r.pointerCanvasPos[0],c=r.pointerCanvasPos[1],h=r.pointerCanvasPos[0],d=r.pointerCanvasPos[1]}function b(){u.pickCursorPos=r.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(p=!0,f.set(u.pickResult.worldPos)):p=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!1}}),g.addEventListener("mousedown",this._mouseDownHandler=function(e){if(s.active&&s.pointerEnabled)switch(e.which){case 1:m[t.input.KEY_SHIFT]||s.planView?(o=!0,_()):(o=!0,_(!1));break;case 2:a=!0,_();break;case 3:l=!0,s.panRightClick&&_()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(){if(s.active&&s.pointerEnabled&&(o||a||l)){var e=t.canvas.boundary,i=e[2],u=e[3],h=r.pointerCanvasPos[0],d=r.pointerCanvasPos[1];if(m[t.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l){var v=h-A,g=d-c,_=t.camera;if("perspective"===_.projection){var y=Math.abs(p?$.lenVec3($.subVec3(f,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(_.perspective.fov/2*Math.PI/180);n.panDeltaX+=1.5*v*y/u,n.panDeltaY+=1.5*g*y/u}else n.panDeltaX+=.5*_.ortho.scale*(v/u),n.panDeltaY+=.5*_.ortho.scale*(g/u)}else!o||a||l||s.planView||(s.firstPerson?(n.rotateDeltaY-=(h-A)/i*s.dragRotationRate/2,n.rotateDeltaX+=(d-c)/u*(s.dragRotationRate/4)):(n.rotateDeltaY-=(h-A)/i*(1.5*s.dragRotationRate),n.rotateDeltaX+=(d-c)/u*(1.5*s.dragRotationRate)));A=h,c=d}}),g.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){s.active&&s.pointerEnabled&&r.mouseover&&(v=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:o=!1,a=!1,l=!1}}),g.addEventListener("mouseup",this._mouseUpHandler=function(e){if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var i=e.target,s=0,r=0,n=0,o=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,n+=i.scrollLeft,o+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+n-s,t[1]=e.pageY+o-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Ed);var t=Ed[0],r=Ed[1];Math.abs(t-h)<3&&Math.abs(r-d)<3&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Ed,event:e},!0)}g.style.removeProperty("cursor")}}),g.addEventListener("mouseenter",this._mouseEnterHandler=function(){s.active&&s.pointerEnabled});var B=1/60,x=null;g.addEventListener("wheel",this._mouseWheelHandler=function(e){if(s.active&&s.pointerEnabled){var t=performance.now()/1e3,i=null!==x?t-x:0;x=t,i>.05&&(i=.05),i0?i.cameraFlight.flyTo(Ld,(function(){i.pivotController.getPivoting()&&s.followPointer&&i.pivotController.showPivot()})):(i.cameraFlight.jumpTo(Ld),i.pivotController.getPivoting()&&s.followPointer&&i.pivotController.showPivot())}}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),Od=function(){function e(t,i,s,r,n){var o=this;w(this,e),this._scene=t;var a=i.pickController,l=i.pivotController,u=i.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;var A=!1,c=!1,h=this._scene.canvas.canvas,d=function(e){var s;e&&e.worldPos&&(s=e.worldPos);var r=e&&e.entity?e.entity.aabb:t.aabb;if(s){var n=t.camera;$.subVec3(n.eye,n.look,[]),i.cameraFlight.flyTo({aabb:r})}else i.cameraFlight.flyTo({aabb:r})},p=t.tickify(this._canvasMouseMoveHandler=function(e){if(s.active&&s.pointerEnabled&&!A&&!c){var i=u.hasSubs("hover"),n=u.hasSubs("hoverEnter"),l=u.hasSubs("hoverOut"),h=u.hasSubs("hoverOff"),d=u.hasSubs("hoverSurface"),p=u.hasSubs("hoverSnapOrSurface");if(i||n||l||h||d||p)if(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=d,a.scheduleSnapOrPick=p,a.update(),a.pickResult){if(a.pickResult.entity){var f=a.pickResult.entity.id;o._lastPickedEntityId!==f&&(void 0!==o._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),u.fire("hoverEnter",a.pickResult,!0),o._lastPickedEntityId=f)}u.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&u.fire("hoverSurface",a.pickResult,!0)}else void 0!==o._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),o._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}});h.addEventListener("mousemove",p),h.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(A=!0),3===e.which&&(c=!0),1===e.which&&s.active&&s.pointerEnabled&&(r.mouseDownClientX=e.clientX,r.mouseDownClientY=e.clientY,r.mouseDownCursorX=r.pointerCanvasPos[0],r.mouseDownCursorY=r.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===e.which))){var i=a.pickResult;i&&i.worldPos?(l.setPivotPos(i.worldPos),l.startPivot()):(s.smartPivot?l.setCanvasPivotPos(r.pointerCanvasPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(A=!1),3===e.which&&(c=!1),l.getPivoting()&&l.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(s.active&&s.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-r.mouseDownClientX)>3||Math.abs(e.clientY-r.mouseDownClientY)>3)))){var n=u.hasSubs("picked"),A=u.hasSubs("pickedNothing"),c=u.hasSubs("pickedSurface"),h=u.hasSubs("doublePicked"),p=u.hasSubs("doublePickedSurface"),f=u.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||h||p||f))return(n||A||c)&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=c,a.update(),a.pickResult?(u.fire("picked",a.pickResult,!0),a.pickedSurface&&u.fire("pickedSurface",a.pickResult,!0)):u.fire("pickedNothing",{canvasPos:r.pointerCanvasPos},!0)),void(o._clicks=0);if(o._clicks++,1===o._clicks){a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo,a.schedulePickSurface=c,a.update();var v=a.pickResult,g=a.pickedSurface;o._timeout=setTimeout((function(){v?(u.fire("picked",v,!0),g&&(u.fire("pickedSurface",v,!0),!s.firstPerson&&s.followPointer&&(i.pivotController.setPivotPos(v.worldPos),i.pivotController.startPivot()&&i.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:r.pointerCanvasPos},!0),o._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==o._timeout&&(window.clearTimeout(o._timeout),o._timeout=null),a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo||h||p,a.schedulePickSurface=a.schedulePickEntity&&p,a.update(),a.pickResult){if(u.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&u.fire("doublePickedSurface",a.pickResult,!0),s.doublePickFlyTo&&(d(a.pickResult),!s.firstPerson&&s.followPointer)){var m=a.pickResult.entity.aabb,_=$.getAABB3Center(m);i.pivotController.setPivotPos(_),i.pivotController.startPivot()&&i.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:r.pointerCanvasPos},!0),s.doublePickFlyTo&&(d(),!s.firstPerson&&s.followPointer)){var y=t.aabb,b=$.getAABB3Center(y);i.pivotController.setPivotPos(b),i.pivotController.startPivot()&&i.pivotController.showPivot()}o._clicks=0}}},!1)}return C(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Nd=function(){function e(t,i,s,r,n){w(this,e),this._scene=t;var o=t.input,a=[],l=t.canvas.canvas,u=!0;this._onSceneMouseMove=o.on("mousemove",(function(){u=!0})),this._onSceneKeyDown=o.on("keydown",(function(e){s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&r.mouseover&&(a[e]=!0,e===o.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(function(e){s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&(a[e]=!1,e===o.KEY_SHIFT&&(l.style.cursor=null),i.pivotController.getPivoting()&&i.pivotController.endPivot())})),this._onTick=t.on("tick",(function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&r.mouseover){var l=i.cameraControl,A=e.deltaTime/1e3;if(!s.planView){var c=l._isKeyDownForAction(l.ROTATE_Y_POS,a),h=l._isKeyDownForAction(l.ROTATE_Y_NEG,a),d=l._isKeyDownForAction(l.ROTATE_X_POS,a),p=l._isKeyDownForAction(l.ROTATE_X_NEG,a),f=A*s.keyboardRotationRate;(c||h||d||p)&&(!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),c?n.rotateDeltaY+=f:h&&(n.rotateDeltaY-=f),d?n.rotateDeltaX+=f:p&&(n.rotateDeltaX-=f),!s.firstPerson&&s.followPointer&&i.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){var v=l._isKeyDownForAction(l.DOLLY_BACKWARDS,a),g=l._isKeyDownForAction(l.DOLLY_FORWARDS,a);if(v||g){var m=A*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),g?n.dollyDelta-=m:v&&(n.dollyDelta+=m),u&&(r.followPointerDirty=!0,u=!1)}}var _=l._isKeyDownForAction(l.PAN_FORWARDS,a),y=l._isKeyDownForAction(l.PAN_BACKWARDS,a),b=l._isKeyDownForAction(l.PAN_LEFT,a),B=l._isKeyDownForAction(l.PAN_RIGHT,a),x=l._isKeyDownForAction(l.PAN_UP,a),w=l._isKeyDownForAction(l.PAN_DOWN,a),P=(a[o.KEY_ALT]?.3:1)*A*s.keyboardPanRate;(_||y||b||B||x||w)&&(!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),w?n.panDeltaY+=P:x&&(n.panDeltaY+=-P),B?n.panDeltaX+=-P:b&&(n.panDeltaX+=P),y?n.panDeltaZ+=P:_&&(n.panDeltaZ+=-P))}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),Qd=$.vec3(),Hd=function(){function e(t,i,s,r,n){w(this,e),this._scene=t;var o=t.camera,a=i.pickController,l=i.pivotController,u=i.panController,A=1,c=1,h=null;this._onTick=t.on("tick",(function(){if(s.active&&s.pointerEnabled){var e="default";if(Math.abs(n.dollyDelta)<.001&&(n.dollyDelta=0),Math.abs(n.rotateDeltaX)<.001&&(n.rotateDeltaX=0),Math.abs(n.rotateDeltaY)<.001&&(n.rotateDeltaY=0),0===n.rotateDeltaX&&0===n.rotateDeltaY||(n.dollyDelta=0),s.followPointer&&--A<=0&&(A=1,0!==n.dollyDelta)){if(0===n.rotateDeltaY&&0===n.rotateDeltaX&&s.followPointer&&r.followPointerDirty&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?h=a.pickResult.worldPos:(c=1,h=null),r.followPointerDirty=!1),h){var i=Math.abs($.lenVec3($.subVec3(h,t.camera.eye,Qd)));c=i/s.dollyProximityThreshold}cs.longTapRadius||Math.abs(g)>s.longTapRadius)&&(clearTimeout(r.longTouchTimeout),r.longTouchTimeout=null),s.planView){var m=t.camera;if("perspective"===m.projection){var _=Math.abs(t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);n.panDeltaX+=v*_/l*s.touchPanRate,n.panDeltaY+=g*_/l*s.touchPanRate}else n.panDeltaX+=.5*m.ortho.scale*(v/l)*s.touchPanRate,n.panDeltaY+=.5*m.ortho.scale*(g/l)*s.touchPanRate}else n.rotateDeltaY-=v/a*(1*s.dragRotationRate),n.rotateDeltaX+=g/l*(1.5*s.dragRotationRate)}else if(2===p){var y=d[0],b=d[1];Gd(y,u),Gd(b,A);var B=$.geometricMeanVec2(h[0],h[1]),x=$.geometricMeanVec2(u,A),w=$.vec2();$.subVec2(B,x,w);var P=w[0],C=w[1],M=t.camera,F=$.distVec2([y.pageX,y.pageY],[b.pageX,b.pageY]),E=($.distVec2(h[0],h[1])-F)*s.touchDollyRate;if(n.dollyDelta=E,Math.abs(E)<1)if("perspective"===M.projection){var k=o.pickResult?o.pickResult.worldPos:t.center,I=Math.abs($.lenVec3($.subVec3(k,t.camera.eye,[])))*Math.tan(M.perspective.fov/2*Math.PI/180);n.panDeltaX-=P*I/l*s.touchPanRate,n.panDeltaY-=C*I/l*s.touchPanRate}else n.panDeltaX-=.5*M.ortho.scale*(P/l)*s.touchPanRate,n.panDeltaY-=.5*M.ortho.scale*(C/l)*s.touchPanRate;r.pointerCanvasPos=x}for(var D=0;D-1&&t-c<150&&(h>-1&&c-h<325?(Kd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("doublePicked",a.pickResult),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult),s.doublePickFlyTo&&p(a.pickResult)):(l.fire("doublePickedNothing"),s.doublePickFlyTo&&p()),h=-1):$.distVec2(u[0],A)<4&&(Kd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("picked",a.pickResult),a.pickedSurface&&l.fire("pickedSurface",a.pickResult)):l.fire("pickedNothing"),h=t),c=-1),u.length=i.length;for(var d=0,f=i.length;d1&&void 0!==arguments[1]?arguments[1]:{};w(this,i),(s=t.call(this,e,r)).PAN_LEFT=0,s.PAN_RIGHT=1,s.PAN_UP=2,s.PAN_DOWN=3,s.PAN_FORWARDS=4,s.PAN_BACKWARDS=5,s.ROTATE_X_POS=6,s.ROTATE_X_NEG=7,s.ROTATE_Y_POS=8,s.ROTATE_Y_NEG=9,s.DOLLY_FORWARDS=10,s.DOLLY_BACKWARDS=11,s.AXIS_VIEW_RIGHT=12,s.AXIS_VIEW_BACK=13,s.AXIS_VIEW_LEFT=14,s.AXIS_VIEW_FRONT=15,s.AXIS_VIEW_TOP=16,s.AXIS_VIEW_BOTTOM=17,s._keyMap={},s.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},s._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},s._states={pointerCanvasPos:$.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:$.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},s._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var n=s.scene;return s._controllers={cameraControl:b(s),pickController:new Fd(b(s),s._configs),pivotController:new Md(n,s._configs),panController:new yd(n),cameraFlight:new Hh(b(s),{duration:.5})},s._handlers=[new Vd(s.scene,s._controllers,s._configs,s._states,s._updates),new zd(s.scene,s._controllers,s._configs,s._states,s._updates),new kd(s.scene,s._controllers,s._configs,s._states,s._updates),new Ud(s.scene,s._controllers,s._configs,s._states,s._updates),new Od(s.scene,s._controllers,s._configs,s._states,s._updates),new Wd(s.scene,s._controllers,s._configs,s._states,s._updates),new Nd(s.scene,s._controllers,s._configs,s._states,s._updates)],s._cameraUpdater=new Hd(s.scene,s._controllers,s._configs,s._states,s._updates),s.navMode=r.navMode,r.planView&&(s.planView=r.planView),s.constrainVertical=r.constrainVertical,r.keyboardLayout?s.keyboardLayout=r.keyboardLayout:s.keyMap=r.keyMap,s.doublePickFlyTo=r.doublePickFlyTo,s.panRightClick=r.panRightClick,s.active=r.active,s.followPointer=r.followPointer,s.rotationInertia=r.rotationInertia,s.keyboardPanRate=r.keyboardPanRate,s.touchPanRate=r.touchPanRate,s.keyboardRotationRate=r.keyboardRotationRate,s.dragRotationRate=r.dragRotationRate,s.touchDollyRate=r.touchDollyRate,s.dollyInertia=r.dollyInertia,s.dollyProximityThreshold=r.dollyProximityThreshold,s.dollyMinSpeed=r.dollyMinSpeed,s.panInertia=r.panInertia,s.pointerEnabled=!0,s.keyboardDollyRate=r.keyboardDollyRate,s.mouseWheelDollyRate=r.mouseWheelDollyRate,s}return C(i,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",le.isString(e)){var t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{var s=e;this._keyMap=s}}},{key:"_isKeyDownForAction",value:function(e,t){var i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(var s=0,r=i.length;s0&&void 0!==arguments[0]?arguments[0]:{};this._controllers.pivotController.enablePivotSphere(e)}},{key:"disablePivotSphere",value:function(){this._controllers.pivotController.disablePivotSphere()}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),f(B(i.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var i=this.metaScene,s=e.properties;if(e.propertySets)for(var r=0,n=e.propertySets.length;r0?ep(t):null,o=i&&i.length>0?ep(i):null;return function e(t){if(t){var i=!0;(o&&o[t.type]||n&&!n[t.type])&&(i=!1),i&&s.push(t.id);var r=t.children;if(r)for(var a=0,l=r.length;a * Copyright (c) 2022 Niklas von Hertzen