From 9511189e9fccaa94dd157aa39bbb06986e672004 Mon Sep 17 00:00:00 2001 From: lindsay Date: Sun, 29 Oct 2023 01:29:26 +0200 Subject: [PATCH] Rebuild --- dist/xeokit-bim-viewer.es.js | 24 ++++++++++++------------ dist/xeokit-bim-viewer.min.es.js | 4 ++-- dist/xeokit-bim-viewer.min.umd.js | 4 ++-- dist/xeokit-bim-viewer.umd.js | 24 ++++++++++++------------ 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/dist/xeokit-bim-viewer.es.js b/dist/xeokit-bim-viewer.es.js index 59a1ae4c..3d78fdc1 100644 --- a/dist/xeokit-bim-viewer.es.js +++ b/dist/xeokit-bim-viewer.es.js @@ -55587,7 +55587,7 @@ class TrianglesInstancingLayer { */ constructor(cfg) { - console.info("Creating TrianglesInstancingLayer"); + // console.info("Creating TrianglesInstancingLayer"); /** * Owner model @@ -74425,7 +74425,7 @@ class SceneModel extends Component { return dtxLayer; } } - console.info(`[SceneModel ${this.id}]: creating TrianglesDataTextureLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesDataTextureLayer`); dtxLayer = new TrianglesDataTextureLayer(this, {layerIndex: 0, origin}); // layerIndex is set in #finalize() this._dtxLayers[layerId] = dtxLayer; this.layerList.push(dtxLayer); @@ -74448,7 +74448,7 @@ class SceneModel extends Component { while (!vboBatchingLayer) { switch (cfg.primitive) { case "triangles": - console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); vboBatchingLayer = new TrianglesBatchingLayer({ model, textureSet, @@ -74463,7 +74463,7 @@ class SceneModel extends Component { }); break; case "solid": - console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); vboBatchingLayer = new TrianglesBatchingLayer({ model, textureSet, @@ -74478,7 +74478,7 @@ class SceneModel extends Component { }); break; case "surface": - console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); vboBatchingLayer = new TrianglesBatchingLayer({ model, textureSet, @@ -74493,7 +74493,7 @@ class SceneModel extends Component { }); break; case "lines": - console.info(`[SceneModel ${this.id}]: creating LinesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating LinesBatchingLayer`); vboBatchingLayer = new LinesBatchingLayer({ model, layerIndex: 0, // This is set in #finalize() @@ -74505,7 +74505,7 @@ class SceneModel extends Component { }); break; case "points": - console.info(`[SceneModel ${this.id}]: creating PointsBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating PointsBatchingLayer`); vboBatchingLayer = new PointsBatchingLayer({ model, layerIndex: 0, // This is set in #finalize() @@ -74559,7 +74559,7 @@ class SceneModel extends Component { while (!vboInstancingLayer) { switch (geometry.primitive) { case "triangles": - console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer = new TrianglesInstancingLayer({ model, textureSet, @@ -74570,7 +74570,7 @@ class SceneModel extends Component { }); break; case "solid": - console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer = new TrianglesInstancingLayer({ model, textureSet, @@ -74581,7 +74581,7 @@ class SceneModel extends Component { }); break; case "surface": - console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer = new TrianglesInstancingLayer({ model, textureSet, @@ -74592,7 +74592,7 @@ class SceneModel extends Component { }); break; case "lines": - console.info(`[SceneModel ${this.id}]: creating LinesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating LinesInstancingLayer`); vboInstancingLayer = new LinesInstancingLayer({ model, textureSet, @@ -74602,7 +74602,7 @@ class SceneModel extends Component { }); break; case "points": - console.info(`[SceneModel ${this.id}]: creating PointsInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating PointsInstancingLayer`); vboInstancingLayer = new PointsInstancingLayer({ model, textureSet, diff --git a/dist/xeokit-bim-viewer.min.es.js b/dist/xeokit-bim-viewer.min.es.js index aa082f0d..75f6e4e6 100644 --- a/dist/xeokit-bim-viewer.min.es.js +++ b/dist/xeokit-bim-viewer.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 s{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class i{constructor(){this.items=[]}}class r{constructor(e,t,s,i,r){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=i,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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const o=this._getNextId(),n=new s(o);for(let s=0,o=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new r(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(i);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);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,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let 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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}let a=!0,l=a?Float64Array:Float32Array;const h=new l(16),c=new l(16),A=new l(4),u={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 s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new 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,s){const i=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,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new l(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>u.dotVec4(e,e),lenVec4:e=>Math.sqrt(u.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=>u.dotVec3(e,e),sqLenVec2:e=>u.dotVec2(e,e),lenVec3:e=>Math.sqrt(u.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,s)=>u.lenVec3(u.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(u.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,s)=>u.lenVec2(u.subVec2(t,s,e))})(),rcpVec3:(e,t)=>u.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/u.lenVec4(e);return u.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/u.lenVec3(e);return u.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/u.lenVec2(e);return u.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=u.dotVec3(e,t)/Math.sqrt(u.sqLenVec3(e)*u.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=u.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=u.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=u.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||u.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:()=>u.m4s(0),setMat4ToOnes:()=>u.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,s,i)=>u.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>u.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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>u.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],E=e[14],y=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],D=t[7],b=t[8],C=t[9],N=t[10],O=t[11],S=t[12],x=t[13],w=t[14],B=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*E,s[3]=g*n+v*c+I*d+_*y,s[4]=T*i+R*a+P*A+D*f,s[5]=T*r+R*l+P*u+D*m,s[6]=T*o+R*h+P*p+D*E,s[7]=T*n+R*c+P*d+D*y,s[8]=b*i+C*a+N*A+O*f,s[9]=b*r+C*l+N*u+O*m,s[10]=b*o+C*h+N*p+O*E,s[11]=b*n+C*c+N*d+O*y,s[12]=S*i+x*a+w*A+B*f,s[13]=S*r+x*l+w*u+B*m,s[14]=S*o+x*h+w*p+B*E,s[15]=S*n+x*c+w*d+B*y,s},mulMat3(e,t,s){s||(s=new l(9));const i=e[0],r=e[3],o=e[6],n=e[1],a=e[4],h=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],E=t[4],y=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*E+o*v,s[6]=i*f+r*y+o*I,s[1]=n*p+a*m+h*g,s[4]=n*d+a*E+h*v,s[7]=n*f+a*y+h*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*E+u*v,s[8]=c*f+A*y+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=u.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],E=e[15],y=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,D=c*E-p*d,b=A*m-u*f,C=A*E-p*f,N=u*E-p*m,O=1/(y*N-g*C+v*b+I*D-_*P+T*R);return t[0]=(a*N-l*C+h*b)*O,t[1]=(-i*N+r*C-o*b)*O,t[2]=(f*T-m*_+E*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*N+l*D-h*P)*O,t[5]=(s*N-r*D+o*P)*O,t[6]=(-d*T+m*v-E*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*C-a*D+h*R)*O,t[9]=(-s*C+i*D-o*R)*O,t[10]=(d*_-f*v+E*y)*O,t[11]=(-c*_+A*v-p*y)*O,t[12]=(-n*b+a*P-l*R)*O,t[13]=(s*b-i*P+r*R)*O,t[14]=(-d*I+f*g-m*y)*O,t[15]=(c*I-A*g+u*y)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||u.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||u.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.translationMat4v(e,r))})(),translationMat4s:(e,t)=>u.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>u.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=u.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,p,d,f,m;return c=a*l,A=l*h,p=h*a,d=a*r,f=l*r,m=h*r,(s=s||u.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*p-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*p+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>u.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=u.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=u.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>u.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=u.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,p=i*h,d=r*l,f=r*h,m=o*h,E=n*a,y=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=p-y,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+E,s[7]=0,s[8]=p+y,s[9]=f-E,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=u.vec4()){const i=u.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],p=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,p),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,p),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,p),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,p),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,p))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,p),s[1]=0)),s},composeMat4:(e,t,s,i=u.mat4())=>(u.quaternionToRotationMat4(t,i),u.scaleMat4v(s,i),u.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=u.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=u.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=u.lenVec3(e);u.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,u.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=u.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],p=t[2];if(r===c&&o===A&&n===p)return u.identityMat4();let d,f,m,E,y,g,v,I,_,T;return d=r-c,f=o-A,m=n-p,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,E=l*m-h*f,y=h*d-a*m,g=a*f-l*d,T=Math.sqrt(E*E+y*y+g*g),T?(T=1/T,E*=T,y*=T,g*=T):(E=0,y=0,g=0),v=f*g-m*y,I=m*E-d*g,_=d*y-f*E,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=E,i[1]=v,i[2]=d,i[3]=0,i[4]=y,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(E*r+y*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>u.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=u.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];u.addVec4(r,i,h),u.subVec4(r,i,c);const o=2*i[2],n=c[0],a=c[1],l=c[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=h[0]/n,s[9]=h[1]/a,s[10]=-h[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],u.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,s=u.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=u.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],E=e[8],y=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),s=new l(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||u.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||u.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=u.vec4()){const i=e[0]*u.DEGTORAD/2,r=e[1]*u.DEGTORAD/2,o=e[2]*u.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=u.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const p=s+n+c;return p>0?(A=.5/Math.sqrt(p+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=u.vec4()){const i=Math.sqrt(u.dotVec3(e,e)*u.dotVec3(t,t));let r=i+u.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):u.cross3Vec3(e,t,s),s[3]=r,u.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=u.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new l(16);return(t,s,i)=>(i=i||u.vec3(),u.quaternionToRotationMat4(t,e),u.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=u.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=u.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,p=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-p*-a,s[1]=A*h+d*-a+p*-n-c*-l,s[2]=p*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=u.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,p=n*s,d=a*s,f=l*s,m=a*i,E=l*i,y=l*r;return t[0]=1-(m+y),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(p+y),t[6]=E+h,t[8]=f+c,t[9]=E-h,t[10]=1-(p+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,E=o*l;return t[0]=1-(u+d),t[4]=c-E,t[8]=A+m,t[1]=c+E,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=u.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>u.normalizeQuaternion(u.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=u.vec4()){const s=(e=u.normalizeQuaternion(e,A))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,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,s,i)=>new l([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],E=e[9],y=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new l(3),t=new l(3),s=new l(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],u.subVec3(t,e,s),Math.abs(u.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=u.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(u.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||u.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||u.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=u.AABB3())=>(e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MAX_DOUBLE,e[3]=u.MIN_DOUBLE,e[4]=u.MIN_DOUBLE,e[5]=u.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=u.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,s,i)=>{s=s||u.AABB3();let r,o,n,a=u.MAX_DOUBLE,l=u.MAX_DOUBLE,h=u.MAX_DOUBLE,c=u.MIN_DOUBLE,A=u.MIN_DOUBLE,p=u.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>p&&(p=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=p,s}})(),OBB3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new l(3);return(t,s)=>{s=s||u.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=u.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=u.vec3()){let s=0,i=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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MIN_DOUBLE,e[3]=u.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=u.AABB2()){let s,i,r,o,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+3*e*e*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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=u.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,p=r*l-o*a,d=Math.sqrt(c*c+A*A+p*p);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=p/d),i},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3);return(o,n,a,l,h,c)=>{c=c||u.vec3();const A=u.subVec3(l,a,e),p=u.subVec3(h,a,t),d=u.cross3Vec3(n,p,s),f=u.dotVec3(A,d);if(f<1e-6)return null;const m=u.subVec3(o,a,i),E=u.dotVec3(m,d);if(E<0||E>f)return null;const y=u.cross3Vec3(m,A,r),g=u.dotVec3(n,y);if(g<0||E+g>f)return null;const v=u.dotVec3(p,y)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3);return(r,o,n,a,l,h)=>{h=h||u.vec3(),o=u.normalizeVec3(o,e);const c=u.subVec3(a,n,t),A=u.subVec3(l,n,s),p=u.cross3Vec3(c,A,i);u.normalizeVec3(p,p);const d=-u.dotVec3(n,p),f=-(u.dotVec3(r,p)+d)/u.dotVec3(o,p);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r,o,n,a)=>{const l=u.subVec3(n,r,e),h=u.subVec3(o,r,t),c=u.subVec3(i,r,s),A=u.dotVec3(l,l),p=u.dotVec3(l,h),d=u.dotVec3(l,c),f=u.dotVec3(h,h),m=u.dotVec3(h,c),E=A*f-p*p;if(0===E)return null;const y=1/E,g=(f*d-p*m)*y,v=(A*m-p*d)*y;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=u.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,E=0;for(f=0,m=e.length;f{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let p,d,f,m,E,y,g;for(h=0,c=a.length;h{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const p=1e4;let d,f,m,E,y,g;for(f=0,E=e.length;f{const e=new l(4),t=new l(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,u.transformVec4(s,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],u.transformVec3(s,e,t),u.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),s=new l(4),i=new l(4),r=new l(4),o=new l(4);return(n,a,l,h,c,A)=>{const p=u.mulMat4(l,a,e),d=u.inverseMat4(p,t),f=n.width,m=n.height,E=(h[0]-f/2)/(f/2),y=-(h[1]-m/2)/(m/2);s[0]=E,s[1]=y,s[2]=-1,s[3]=1,u.transformVec4(d,s,i),u.mulVec4Scalar(i,1/i[3]),r[0]=E,r[1]=y,r[2]=1,r[3]=1,u.transformVec4(d,r,o),u.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],u.subVec3(o,i,A),u.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(s,i,r,o,n,a,l)=>{u.canvasPosToWorldRay(s,i,r,n,e,t),u.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),s=new l(4);return(i,r,o,n,a)=>{const l=u.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],u.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let h,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,h=0,c=s.length;hn[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(s.length<20||o>10)return a.triangles=s,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 p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let E=0;for(h=0,c=s.length;h{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};u.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();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 d=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),i=s+e[1],r=s;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),s=new Uint8Array(e);for(var n=0;n=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}},I={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},_=[];let T,R=0,P=0;const D=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(D.scenes[e.id])return void console.error(`[ERROR] Scene ${E.inQuotes(e.id)} already exists`)}else e.id=g.addItem({});D.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;y[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},p.components.scenes++,e.once("destroyed",(()=>{g.removeItem(e.id),delete D.scenes[e.id],delete y[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in D.scenes)D.scenes.hasOwnProperty(t)&&(e=D.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete D.scenes[e.id]))},this.scheduleTask=function(e,t){v.push(e),v.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;v.length>0&&(e<0||i0&&T>0){var t=1e3/T;P+=t,_.push(t),_.length>=30&&(P-=_.shift()),p.frame.fps=Math.round(P/_.length)}!function(e){const t=D.runTasks(e+10),s=D.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=s,p.frame.tasksBudget=10}(e),function(e){for(var t in I.time=e,D.scenes)if(D.scenes.hasOwnProperty(t)){var s=D.scenes[t];I.sceneId=t,I.startTime=s.startTime,I.deltaTime=null!=I.prevTime?I.time-I.prevTime:0,s.fire("tick",I,!0)}I.prevTime=e}(e),function(){const e=D.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=y[n],i||(i=y[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),R=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(b):requestAnimationFrame(b)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(b):requestAnimationFrame(b);class C{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof C))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let 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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+E.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(E.isNumeric(s)||E.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+E.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+E.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+E.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():D.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(u.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){K.set(this._viewPos),K[3]=1,u.transformPoint4(this.scene.camera.projMatrix,K,Y);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+Y[0]/Y[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-Y[1]/Y[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 z?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]),S(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 Z{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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.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,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class q{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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),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.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 s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class J{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+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 $=u.vec3(),ee=u.vec3();class te extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new X(s,t.origin),this._cornerMarker=new X(s,t.corner),this._targetMarker=new X(s,t.target),this._originWorld=u.vec3(),this._cornerWorld=u.vec3(),this._targetWorld=u.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new Z(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new Z(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new J(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,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=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(u.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){const p=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>p||f>p||m>p)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);u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const E=this._container.getBoundingClientRect();for(var r=i.top-E.top,o=i.left-E.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{switch(e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red"),r=!0,o=e.entity,l.set(e.worldPos),h.set(e.canvasPos),this._mouseState){case 0:this.markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this.markerDiv.style.marginTop=e.canvasPos[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(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,i&&(i.visible=!0,i.centerPos=e.cursorPos,i.cursorPos=e.cursorPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class re extends n{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 ie(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,s=e.corner,i=e.target,r=new te(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.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]})),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,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const ne=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class ae extends C{constructor(e,t={}){super(e,t),this._backgroundColor=u.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new oe(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-"+u.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?he.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?he.FS_MAX_FLOAT_PRECISION="mediump":he.FS_MAX_FLOAT_PRECISION="lowp":he.FS_MAX_FLOAT_PRECISION="mediump",he.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),he.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),he.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),he.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),he.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),he.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),he.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),he.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),he.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),he.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){he.SUPPORTED_EXTENSIONS[e]=!0})))}class Ae{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class ue{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function Ee(e){console.error(e.join("\n"))}class ye{constructor(e,t){this.id=fe.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 ue(e,e.VERTEX_SHADER,me(this.source.vertex)),this._fragmentShader=new ue(e,e.FRAGMENT_SHADER,me(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Ee(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Ee(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Ee(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Ee(this.errors);let t,s,i,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 Ee(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.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 ve{constructor(e,t){this.scene=e,this.aabb=u.AABB3(),this.origin=u.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){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new ve(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new ve(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new ye(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),p=Math.random(),d="perspective"===i.camera.projection;Re[0]=o,Re[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,Re),t.uniform1f(this._uRandomSeed,p);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ye(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const i=new Float32Array([1,1,0,1,0,0,1,0]),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 ge(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new ge(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new ge(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const De=new Float32Array(xe(17,[0,1])),be=new Float32Array(xe(17,[1,0])),Ce=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(Se(i,t));return s}(17,4)),Ne=new Float32Array(2);class Oe{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 ye(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new ge(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new ge(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ge(e,e.ELEMENT_ARRAY_BUFFER,i,i.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Ne[0]=n,Ne[1]=a,i.uniform2fv(this._uViewport,Ne),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,be):i.uniform2fv(this._uSampleOffsets,De),i.uniform1fv(this._uSampleWeights,Ce);const A=e.getDepthTexture(),p=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,p,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Se(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function xe(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class we{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(e=null){if(this._touch(e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(e=null){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=i.createTexture();let o;i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e?i.texStorage2D(i.TEXTURE_2D,1,e,t,s):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,s,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,a),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r,depthTexture:o,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,i=null,r=Uint8Array,o=4){const n=e,a=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,l=new r(o),h=this.gl;return h.readPixels(n,a,1,1,s||h.RGBA,i||h.UNSIGNED_BYTE,l,0),l}readArray(e=null,t=null,s=Uint8Array,i=4){const r=new s(this.buffer.width*this.buffer.height*i),o=this.gl;return o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,r,0),r}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=l.size[0],i=t%s-Math.floor(s/2),o=Math.floor(t/s)-Math.floor(s/2),a=Math.sqrt(Math.pow(i,2)+Math.pow(o,2));y.push({x:i,y:o,dist:a,isVertex:r&&n?d[e+3]>p.length/2:r,result:[d[e+0],d[e+1],d[e+2],d[e+3]]})}let g=null,v=null;if(y.length>0){y.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),v=y[0].isVertex?"vertex":"edge",y=y[0].result;const e=p[y[3]],t=e.origin,s=e.coordinateScale;g=[y[0]*s[0]+t[0],y[1]*s[1]+t[1],y[2]*s[2]+t[2]]}if(null===f&&null==g)return null;let _=null;return null!==g&&(_=t.camera.projectWorldPos(g)),{snapType:v,snappedToVertex:"vertex"===v,snappedToEdge:"edge"===v,worldPos:f,snappedWorldPos:g,snappedCanvasPos:_}},this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Te(t,I),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(),i.reset(),i.backfaces=!0,i.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 h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=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()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=(e,t)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",s,!0)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!0)}))}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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 Ue=new e({});class He{constructor(e){this.id=Ue.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){Ue.removeItem(this.id)}}class Ge extends C{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new He({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],s=e[3];this._state.boundary=[0,0,t,s],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class Ve extends C{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),u.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ke extends C{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),u.orthoMat4c(n,a,h,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class je extends C{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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(){u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Qe extends C{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const We=u.vec3(),ze=u.vec3(),Ke=u.vec3(),Ye=u.vec3(),Xe=u.vec3(),Ze=u.vec3(),qe=u.vec4(),Je=u.vec4(),$e=u.vec4(),et=u.mat4(),tt=u.mat4(),st=u.vec3(),it=u.vec3(),rt=u.vec3(),ot=u.vec3();class nt extends C{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new He({deviceMatrix:u.mat4(),hasDeviceMatrix:!1,matrix:u.mat4(),normalMatrix:u.mat4(),inverseMatrix:u.mat4()}),this._perspective=new Ve(this),this._ortho=new ke(this),this._frustum=new je(this),this._customProjection=new Qe(this),this._project=this._perspective,this._eye=u.vec3([0,0,10]),this._look=u.vec3([0,0,0]),this._up=u.vec3([0,1,0]),this._worldUp=u.vec3([0,1,0]),this._worldRight=u.vec3([1,0,0]),this._worldForward=u.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?(u.subVec3(this._eye,this._look,st),u.normalizeVec3(st,it),u.mulVec3Scalar(it,1e3,rt),u.addVec3(this._look,rt,ot),t=ot):t=this._eye,e.hasDeviceMatrix?(u.lookAtMat4v(t,this._look,this._up,tt),u.mulMat4(e.deviceMatrix,tt,e.matrix)):u.lookAtMat4v(t,this._look,this._up,e.matrix),u.inverseMat4(this._state.matrix,this._state.inverseMatrix),u.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=u.subVec3(this._eye,this._look,We);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,et),t=u.transformPoint3(et,t,ze),this.eye=u.addVec3(this._look,t,Ke),this.up=u.transformPoint3(et,this._up,Ye)}orbitPitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._eye,this._look,We);const s=u.cross3Vec3(u.normalizeVec3(t,ze),u.normalizeVec3(this._up,Ke));u.rotationMat4v(.0174532925*e,s,et),t=u.transformPoint3(et,t,Ye),this.up=u.transformPoint3(et,this._up,Xe),this.eye=u.addVec3(t,this._look,Ze)}yaw(e){let t=u.subVec3(this._look,this._eye,We);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,et),t=u.transformPoint3(et,t,ze),this.look=u.addVec3(t,this._eye,Ke),this._gimbalLock&&(this.up=u.transformPoint3(et,this._up,Ye))}pitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._look,this._eye,We);const s=u.cross3Vec3(u.normalizeVec3(t,ze),u.normalizeVec3(this._up,Ke));u.rotationMat4v(.0174532925*e,s,et),this.up=u.transformPoint3(et,this._up,Ze),t=u.transformPoint3(et,t,Ye),this.look=u.addVec3(t,this._eye,Xe)}pan(e){const t=u.subVec3(this._eye,this._look,We),s=[0,0,0];let i;if(0!==e[0]){const r=u.cross3Vec3(u.normalizeVec3(t,[]),u.normalizeVec3(this._up,ze));i=u.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=u.mulVec3Scalar(u.normalizeVec3(this._up,Ke),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=u.mulVec3Scalar(u.normalizeVec3(t,Ye),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=u.addVec3(this._eye,s,Xe),this.look=u.addVec3(this._look,s,Ze)}zoom(e){const t=u.subVec3(this._eye,this._look,We),s=Math.abs(u.lenVec3(t,ze)),i=Math.abs(s+e);if(i<.5)return;const r=u.normalizeVec3(t,Ke);this.eye=u.addVec3(this._look,u.mulVec3Scalar(r,i),Ye)}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=u.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 u.lenVec3(u.subVec3(this._look,this._eye,We))}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=qe,s=Je,i=$e;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,u.mulMat4v4(this.viewMatrix,t,s),u.mulMat4v4(this.projMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class at extends C{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class lt extends at{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new He({type:"dir",dir:u.vec3([1,1,1]),color:u.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=u.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];u.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=u.identityMat4()),u.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 ht extends at{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:u.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 ct extends C{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var At=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();const ut=function(){const e=u.mat4(),t=u.mat4();return function(s,i){i=i||u.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return u.identityMat4(e),u.translationMat4v(s,e),u.identityMat4(t),u.scalingMat4v([a/c,l/c,h/c],t),u.mulMat4(e,t,i),i}}();var pt=function(){const e=u.mat4(),t=u.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[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[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function mt(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function Et(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const yt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=ft(e,a,"floor","ceil"),i=mt(s),o=Et(e,a,i),o>n&&(r=s,n=o),s=ft(e,a,"ceil","ceil"),i=mt(s),o=Et(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},gt=p.memory,vt=u.AABB3();class It extends ct{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new He({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=yt.getPositionsBounds(t.positions),i=yt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=yt.getUVBounds(t.uv),i=yt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=yt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),gt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),gt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ge(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),gt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new ge(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),gt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ge(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),gt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ge(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),gt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=At(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),gt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=u.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),gt.positions+=this._pickTrianglePositionsBuf.numItems,gt.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),yt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=yt.getPositionsBounds(e),i=yt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),yt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),yt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=u.AABB3()),u.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=u.OBB3()),u.positions3ToAABB3(this._state.positions,vt,this._state.positionsDecodeMatrix),u.AABB3ToOBB3(vt,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(),gt.meshes--}}function _t(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return E.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Tt extends C{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Rt={opaque:0,mask:1,blend:2},Pt=["opaque","mask","blend"];class Dt extends Tt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new He({type:"PhongMaterial",ambient:u.vec3([1,1,1]),diffuse:u.vec3([1,1,1]),specular:u.vec3([1,1,1]),emissive:u.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=Rt[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 Pt[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 bt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Ct extends Tt{get type(){return"EmphasisMaterial"}get presets(){return bt}constructor(e,t={}){super(e,t),this._state=new He({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=bt[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(bt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Nt={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 Ot extends Tt{get type(){return"EdgeMaterial"}get presets(){return Nt}constructor(e,t={}){super(e,t),this._state=new He({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=Nt[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(Nt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const St={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 xt extends C{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=u.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return St}set units(e){e||(e="meters");St[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=u.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=u.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 C{constructor(e,t={}){super(e,t),this._supported=he.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 Bt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Mt extends Tt{get type(){return"PointsMaterial"}get presets(){return Bt}constructor(e,t={}){super(e,t),this._state=new He({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=Bt[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(Bt).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 Ft={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Lt extends Tt{get type(){return"LinesMaterial"}get presets(){return Ft}constructor(e,t={}){super(e,t),this._state=new He({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=Ft[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ft).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ut(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Fe(this,{transparent:i,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,i=t.length;e0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=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 "+E.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=u.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],E.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&D.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=Ut(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=Ut(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t{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=u.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){E.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.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);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.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=s.sectionPlanes.length;e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),A=jt(e),u=i.sectionPlanes.length>0,p=kt(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),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(A){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("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&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(p){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=jt(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=kt(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));p&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Vt[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("}")),(A||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 = "+Vt[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Vt[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Vt[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Vt[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Vt[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){h&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),A&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||A)&&(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 s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class Yt{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.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);"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.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;"));i&&(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=s.sectionPlanes.length;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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Xt=new e({}),Zt=u.vec3(),qt=function(e,t){this.id=Xt.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Yt(t),this._allocate(t)},Jt={};qt.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Jt[t];return s||(s=new qt(t,e),Jt[t]=s,p.memory.programs++),s._useCount++,s},qt.prototype.put=function(){0==--this._useCount&&(Xt.removeItem(this.id),this._program&&this._program.destroy(),delete Jt[this._hash],p.memory.programs--)},qt.prototype.webglContextRestored=function(){this._program=null},qt.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._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),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.sectionPlanes.length>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;"));i&&(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=s.sectionPlanes.length;e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const es=new e({}),ts=u.vec3(),ss=function(e,t){this.id=es.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new $t(t),this._allocate(t)},is={};ss.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=is[t];return s||(s=new ss(t,e),is[t]=s,p.memory.programs++),s._useCount++,s},ss.prototype.put=function(){0==--this._useCount&&(es.removeItem(this.id),this._program&&this._program.destroy(),delete is[this._hash],p.memory.programs--)},ss.prototype.webglContextRestored=function(){this._program=null},ss.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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;"),i){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 os=u.vec3(),ns=function(e,t){this._hash=e,this._shaderSource=new rs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},as={};ns.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=as[t];if(!s){if(s=new ns(t,e),s.errors)return console.log(s.errors.join("\n")),null;as[t]=s,p.memory.programs++}return s._useCount++,s},ns.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete as[this._hash],p.memory.programs--)},ns.prototype.webglContextRestored=function(){this._program=null},ns.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},ns.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ye(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 hs=u.vec3(),cs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ls(t),this._allocate(t)},As={};cs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=As[t];if(!s){if(s=new cs(t,e),s.errors)return console.log(s.errors.join("\n")),null;As[t]=s,p.memory.programs++}return s._useCount++,s},cs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete As[this._hash],p.memory.programs--)},cs.prototype.webglContextRestored=function(){this._program=null},cs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 ps=u.vec3(),ds=function(e,t){this._hash=e,this._shaderSource=new us(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},fs={};ds.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=fs[t];if(!s){if(s=new ds(t,e),s.errors)return console.log(s.errors.join("\n")),null;fs[t]=s,p.memory.programs++}return s._useCount++,s},ds.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete fs[this._hash],p.memory.programs--)},ds.prototype.webglContextRestored=function(){this._program=null},ds.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.sectionPlanes.length>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),i){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 Es=function(e,t){this._hash=e,this._shaderSource=new ms(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ys={};Es.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=ys[s];if(!i){if(i=new Es(s,e),i.errors)return console.log(i.errors.join("\n")),null;ys[s]=i,p.memory.programs++}return i._useCount++,i},Es.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ys[this._hash],p.memory.programs--)},Es.prototype.webglContextRestored=function(){this._program=null},Es.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Es.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ye(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Ss=function(){const e=u.vec3(),t=u.vec3(),s=u.vec3(),i=u.vec3(),r=u.vec3(),o=u.vec3(),n=u.vec4(),a=u.vec3(),l=u.vec3(),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3(),E=u.vec4(),y=u.vec4(),g=u.vec4(),v=u.vec3(),I=u.vec3(),_=u.vec3(),T=u.vec3(),R=u.vec3(),P=u.vec3(),D=u.vec3(),b=u.vec3(),C=u.vec3(),N=u.vec3(),S=u.vec3();return function(x,w,B,M){var F=M.primIndex;if(null!=F&&F>-1){const G=x.geometry._state,V=x.scene,k=V.camera,j=V.canvas;if("triangles"===G.primitiveName){M.primitive="triangle";const V=F,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var L=Q[V+0],U=Q[V+1],H=Q[V+2];o[0]=L,o[1]=U,o[2]=H,M.indices=o,z=3*L,K=3*U,Y=3*H}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(yt.decompressPosition(s,e,s),yt.decompressPosition(i,e,i),yt.decompressPosition(r,e,r))}M.canvasPos?u.canvasPosToLocalRay(j.canvas,x.origin?O(w,x.origin):w,B,x.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&u.worldRayToLocalRay(x.worldMatrix,M.origin,M.direction,e,t),u.normalizeVec3(t),u.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,E[0]=n[0],E[1]=n[1],E[2]=n[2],E[3]=1,u.transformVec4(x.worldMatrix,E,y),a[0]=y[0],a[1]=y[1],a[2]=y[2],M.canvasPos&&x.origin&&(a[0]+=x.origin[0],a[1]+=x.origin[1],a[2]+=x.origin[2]),M.worldPos=a,u.transformVec4(k.matrix,y,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,u.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=G.normals;if(X){if(G.compressGeometry){const e=3*L,t=3*U,s=3*H;yt.decompressNormal(X.subarray(e,e+2),c),yt.decompressNormal(X.subarray(t,t+2),A),yt.decompressNormal(X.subarray(s,s+2),p)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],p[0]=X[Y],p[1]=X[Y+1],p[2]=X[Y+2];const e=u.addVec3(u.addVec3(u.mulVec3Scalar(c,h[0],v),u.mulVec3Scalar(A,h[1],I),_),u.mulVec3Scalar(p,h[2],T),R);M.worldNormal=u.normalizeVec3(u.transformVec3(x.worldNormalMatrix,e,P))}const Z=G.uv;if(Z){if(d[0]=Z[2*L],d[1]=Z[2*L+1],f[0]=Z[2*U],f[1]=Z[2*U+1],m[0]=Z[2*H],m[1]=Z[2*H+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(yt.decompressUV(d,e,d),yt.decompressUV(f,e,f),yt.decompressUV(m,e,m))}M.uv=u.addVec3(u.addVec3(u.mulVec2Scalar(d,h[0],D),u.mulVec2Scalar(f,h[1],b),C),u.mulVec2Scalar(m,h[2],N),S)}}}}}();function xs(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],y=[],g=[],v=[];let I,_,T,R,P,D,b,C,N,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,D=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),y.push(P*T),y.push(x),y.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(D+h),m.push(P*R+c);for(I=0;I0){for(N=m.length/3,y.push(0),y.push(1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(t*T),y.push(1),y.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(N=m.length/3,y.push(0),y.push(-1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(s*T),y.push(-1),y.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Ws(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=Ws(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Ws(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Xs(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Xs(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Ws(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Ws(s,this.magFilter)));const a=Ws(s,this.format,this.encoding),l=Ws(s,this.type),h=Ys(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class $s extends C{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new He({texture:new Ks({gl:this.scene.canvas.gl}),matrix:u.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=u.vec2([0,0]),this._scale=u.vec2([1,1]),this._rotate=u.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 Ks({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=u.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=u.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?u.mulMat4(t,s):s),0!==this._rotate&&(s=u.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?u.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Zs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=Zs(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const ei=p.memory,ti=u.AABB3();class si extends ct{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new He({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=u.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=yt.getPositionsBounds(t.positions),o=yt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new ge(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),ei.positions+=s.positionsBuf.numItems,u.positions3ToAABB3(t.positions,this._aabb),u.positions3ToAABB3(r,ti,s.positionsDecodeMatrix),u.AABB3ToOBB3(ti,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new ge(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),ei.colors+=s.colorsBuf.numItems}if(t.uv){const e=yt.getUVBounds(t.uv),r=yt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new ge(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),ei.uvs+=s.uvBuf.numItems}if(t.normals){const e=yt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new ge(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),ei.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),ei.indices+=s.indicesBuf.numItems;const o=At(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),ei.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(),ei.meshes--}}var ii={};function ri(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,y=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,D,b,C=0,N=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],p=[],d=[];let f,m,y,g,v,I,_,T,R,P,D,b;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),y=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(y+a),c.push(g+l),c.push(v+h),p.push(1-_/i),p.push(T/r),I=u.normalizeVec3(u.subVec3([y,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,D=(i+1)*(T-1)+_,b=(i+1)*T+_,d.push(R),d.push(P),d.push(D),d.push(D),d.push(b),d.push(R);return E.apply(e,{positions:c,normals:A,uv:p,indices:d})}ii.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},ii.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(ii.parse._buffToStr(e));window.location.href=s},ii.clone=function(e){return JSON.parse(JSON.stringify(e))},ii.bin={},ii.bin.f=new Float32Array(1),ii.bin.fb=new Uint8Array(ii.bin.f.buffer),ii.bin.rf=function(e,t){for(var s=ii.bin.f,i=ii.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},ii.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},ii.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},ii.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},ii.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},ii.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},ii.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},ii.parse={},ii.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class ni extends C{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=u.vec3(t.pos||[0,0,0]),this._up=u.vec3(t.up||[0,1,0]),this._normal=u.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=u.vec3(),this._rtcPos=u.vec3(),this._imageSize=u.vec2(),this._texture=new $s(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 Qs(this,{matrix:u.inverseMat4(u.lookAtMat4v(this._pos,u.subVec3(this._pos,this._normal,u.mat4()),this._up,u.mat4())),children:[this._bitmapMesh=new Os(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new It(this,ri({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Dt(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 ai=u.vec3(),li=u.vec3(),hi=u.mat4();class ci{constructor(){this.normal=u.vec3(),this.offset=0,this.testVertex=u.vec3()}set(e,t,s,i){const r=1/Math.sqrt(e*e+t*t+s*s);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=s*r,this.offset=i*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class Ai{constructor(){this.planes=[new ci,new ci,new ci,new ci,new ci,new ci]}}function ui(e,t){let s=Ai.INSIDE;const i=ai,r=li;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return Ai.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=Ai.INTERSECT)}return s}Ai.INSIDE=0,Ai.INTERSECT=1,Ai.OUTSIDE=2;class pi extends C{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=u.vec3(),r=x(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,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}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),y=Object.entries(E).map((([e,t])=>({color:e,components:t})));o.components.coloring=y;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=vi(e.location,di),s=vi(e.direction,di);h&&u.negateVec3(s),u.subVec3(t,l),r.yUp&&(t=_i(t),s=_i(s)),new Bs(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];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),s.push(r++),s.push(r++))})),new pi(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=vi(e.location,fi),n=vi(e.normal,mi),a=vi(e.up,Ei),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=_i(o),n=_i(n),a=_i(a)),new ni(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.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&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!1),r.space_boundaries_visible)}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const 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((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=vi(e.perspective_camera.camera_view_point,di),h=vi(e.perspective_camera.camera_direction,di),c=vi(e.perspective_camera.camera_up_vector,di),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=vi(e.orthogonal_camera.camera_view_point,di),h=vi(e.orthogonal_camera.camera_direction,di),c=vi(e.orthogonal_camera.camera_up_vector,di),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),u.subVec3(a,l),r.yUp&&(a=_i(a),h=_i(h),c=_i(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:u.addVec3(a,h,di)}else h=u.addVec3(a,h,di);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.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 s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=u.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function gi(e){return{x:e[0],y:e[1],z:e[2]}}function vi(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ii(e){return new Float64Array([e[0],-e[2],e[1]])}function _i(e){return new Float64Array([e[0],e[2],-e[1]])}const Ti=u.vec3(),Ri=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class Pi extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new X(s,t.origin),this._targetMarker=new X(s,t.target),this._originWorld=u.vec3(),this._targetWorld=u.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 i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new Z(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new Z(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new Z(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new Z(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new J(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new J(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new J(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new J(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;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&&(u.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);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=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,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,E=s.unitsInfo[m].abbrev;for(var p=0,d=i.length;p{r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this._markerDiv.style.marginTop=e.canvasPos[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red")):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.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.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null)}destroy(){this.deactivate(),super.destroy()}}class Ci extends n{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._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 bi(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,s=e.target,i=new Pi(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.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,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}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,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(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,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=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),i=!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 Oi{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const i=Si(e,s);return i?t?xi(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=Si(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=xi(r,[t]),s&&(r=xi(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[t];i||(i={},this._eventSubs[t]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function Si(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?Ui._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(u.subVec3(i.eye,i.look,Li),i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Mi),i.look=u.subVec3(Mi,Li,Bi)):this._flyingLook&&(i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Bi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Fi)):this._flyingEyeLookUp&&(i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Mi),i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Bi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Fi)),this._projection2){const t="ortho"===this._projection2?Ui._easeOutExpo(e,0,1,1):Ui._easeInCubic(e,0,1,1);i.customProjection.matrix=u.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();D.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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 Hi extends C{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Ui(this),this._t=0,this.state=Hi.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case Hi.SCRUBBING:return;case Hi.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=Hi.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Hi.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=Hi.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=Hi.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=Hi.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=Hi.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=Hi.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Hi.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Hi.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Hi.STOPPED=0,Hi.SCRUBBING=1,Hi.PLAYING=2,Hi.PLAYING_TO=3,u.vec3(),u.vec3(),u.vec3(),u.vec3([0,-1,0]),u.vec4([0,0,0,1]);const Gi=u.vec3();class Vi{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,s){this.numObjects=0,this._mask=s?E.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const n=t._sectionPlanesState.sectionPlanes,a=r*o,l=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;Yi[0]=s,Yi[1]=i,Yi[2]=t.blendCutoff,Yi[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Yi),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===Wi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Wi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Wi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?Ki:zi)}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 $i extends Ji{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class er extends $i{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class tr extends Ji{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class sr extends tr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class ir extends Ji{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class rr extends Ji{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class or extends Ji{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class nr extends Ji{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class ar extends $i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class lr extends $i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.sectionPlanes.length>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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 cr extends er{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class Ar extends er{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class ur extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class pr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class dr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class fr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class mr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class Er extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class yr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class gr extends $i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class Ir extends $i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.sectionPlanes.length>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=i.sectionPlanes.length;e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;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=s.lights.length;e5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Pr=u.mat4(),Dr=u.mat4();function br(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,p=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function Or(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const Sr=u.vec3(),xr=u.vec3(),wr=u.vec3(),Br=u.vec3(),Mr=u.mat4();class Fr extends Ji{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Sr;let m,E;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=xr;if(l){const e=wr;u.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=O(d,t,Mr),E=Br,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Lr=u.vec3(),Ur=u.vec3(),Hr=u.vec3(),Gr=u.vec3(),Vr=u.mat4();class kr extends Ji{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Lr;let m,E;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=Ur;if(l){const e=Hr;u.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=O(d,t,Vr),E=Gr,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class jr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Fr(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new kr(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Fr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new kr(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Qr={};const Wr=u.mat4(),zr=u.mat4(),Kr=u.vec4([0,0,0,1]),Yr=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.OBB3();const Xr=u.vec3(),Zr=u.vec3(),qr=u.vec3(),Jr=u.vec3(),$r=u.vec3(),eo=u.vec3(),to=u.vec3();class so{constructor(e){console.info("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Tr[t];return s||(s=new _r(e),Tr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Tr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=Qr[t];return s||(s=new jr(e),Qr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Qr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Rr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new He({origin:u.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=u.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=u.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=u.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=u.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)for(let e=0,t=r.length;e0){const e=Wr;m?u.inverseMat4(u.transposeMat4(m,zr),e):u.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,p=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=Nr(d,"floor","ceil"),a=Or(n),h=o(d,a),h>c&&(l=n,c=h),n=Nr(d,"ceil","ceil"),a=Or(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,i,i.length,v.normals,v.normals.length)}if(a)for(let e=0,t=a.length;e0)for(let e=0,t=o.length;e0)for(let e=0,t=n.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):br(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=u.mat4());if(e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new ge(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new ge(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=yt.getUVBounds(s.uv),r=yt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=u.mat3(r.decodeMatrix),e.uvBuf=new ge(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new ge(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,i,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;ey)&&(y=e,i.set(g),r&&u.triangleNormal(d,f,m,r),E=!0)}}return E&&r&&(u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),E}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 io extends tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class ro extends tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,r;const o=t.sectionPlanes.length>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,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class no extends sr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class ao extends sr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class lo extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class ho extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class co extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class Ao extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class uo extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 po extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class fo extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const mo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Eo extends tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),i.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 = "+mo[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+mo[i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class go extends tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.sectionPlanes.length>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=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Co=u.vec3(),No=u.vec3(),Oo=u.vec3(),So=u.vec3(),xo=u.mat4();class wo extends Ji{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Co;let m,E;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=No;if(l){const e=u.transformPoint3(c,l,Oo);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=O(d,t,xo),E=So,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Bo{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new bo(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new wo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new bo(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new wo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Mo={};const Fo=new Uint8Array(4),Lo=new Float32Array(1),Uo=u.vec4([0,0,0,1]),Ho=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]);const Go=new Float32Array(3),Vo=u.vec3(),ko=u.vec3(),jo=u.vec3(),Qo=u.vec3(),Wo=u.vec3(),zo=u.vec3(),Ko=u.vec3();class Yo{constructor(e){console.info("Creating TrianglesInstancingLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Io[t];return s||(s=new vo(e),Io[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Io[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=Mo[t];return s||(s=new Bo(e),Mo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Mo[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new He({numInstances:0,obb:u.OBB3(),origin:u.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf: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._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=u.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,i=e.roughness,r=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,o=e.meshMatrix,n=e.aabb,a=e.pickColor;if(this._finalized)throw"Already finalized";const l=t[0],h=t[1],c=t[2];if(this._colors.push(l),this._colors.push(h),this._colors.push(c),this._colors.push(r),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=i?i:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(o[0]),this._modelMatrixCol0.push(o[4]),this._modelMatrixCol0.push(o[8]),this._modelMatrixCol0.push(o[12]),this._modelMatrixCol1.push(o[1]),this._modelMatrixCol1.push(o[5]),this._modelMatrixCol1.push(o[9]),this._modelMatrixCol1.push(o[13]),this._modelMatrixCol2.push(o[2]),this._modelMatrixCol2.push(o[6]),this._modelMatrixCol2.push(o[10]),this._modelMatrixCol2.push(o[14]),this._state.geometry.normals){let e=u.transposeMat4(o,u.mat4()),t=u.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]);const A=this._state.geometry.positionsCompressed.length,p=this._state.geometry.positionsCompressed,d=this._state.geometry.positionsDecodeMatrix;for(let e=0;e0){let t=!1;e.colorsBuf=new ge(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new ge(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new ge(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new ge(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=u.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new ge(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new ge(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new ge(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fo[0]=t[0],Fo[1]=t[1],Fo[2]=t[2],Fo[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Fo,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&B),r=!!(t&H),o=!!(t&G),n=!!(t&V),a=!!(t&k),l=!!(t&F),h=!!(t&M);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Wi.NOT_RENDERED:s?Wi.COLOR_TRANSPARENT:Wi.COLOR_OPAQUE,A=!i||h?Wi.NOT_RENDERED:n?Wi.SILHOUETTE_SELECTED:o?Wi.SILHOUETTE_HIGHLIGHTED:r?Wi.SILHOUETTE_XRAYED:Wi.NOT_RENDERED;let u=0;u=!i||h?Wi.NOT_RENDERED:n?Wi.EDGES_SELECTED:o?Wi.EDGES_HIGHLIGHTED:r?Wi.EDGES_XRAYED:a?s?Wi.EDGES_COLOR_TRANSPARENT:Wi.EDGES_COLOR_OPAQUE:Wi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Wi.PICK:Wi.NOT_RENDERED)<<12,p|=(t&L?1:0)<<16,Lo[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(Lo,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Go[0]=t[0],Go[1]=t[1],Go[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Go,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=Uo,p=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&u.triangleNormal(f,m,E,r),y=!0)}}return y&&r&&(u.transformVec3(a.normalMatrix,r,r),u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),y}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 Xo extends or{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Zo extends or{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class qo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Xo(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Zo(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Jo={};class $o{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const en=u.vec4([0,0,0,1]),tn=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.OBB3();class sn{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Jo[t];return s||(s=new qo(e),Jo[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Jo[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new $o(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new He({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=br(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 on extends nr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class nn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new rn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new on(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const an={};const ln=new Uint8Array(4),hn=new Float32Array(1),cn=u.vec4([0,0,0,1]),An=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]);const un=new Float32Array(3);class pn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=an[t];return s||(s=new nn(e),an[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete an[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new He({obb:u.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=u.vec3(e.origin)),this._finalized=!1,this.aabb=u.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,i=e.meshMatrix,r=e.aabb;if(this._finalized)throw"Already finalized";const o=t[0],n=t[1],a=t[2];t[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),u.collapseAABB3(r);const l=this._state.obb,h=l.length;for(let e=0;e0){let t=!1;this._state.colorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";ln[0]=t[0],ln[1]=t[1],ln[2]=t[2],ln[3]=t[3],this._state.colorsBuf.setData(ln,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&B),r=!!(t&H),o=!!(t&G),n=!!(t&V),a=!!(t&k),l=!!(t&F),h=!!(t&M);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Wi.NOT_RENDERED:s?Wi.COLOR_TRANSPARENT:Wi.COLOR_OPAQUE,A=!i||h?Wi.NOT_RENDERED:n?Wi.SILHOUETTE_SELECTED:o?Wi.SILHOUETTE_HIGHLIGHTED:r?Wi.SILHOUETTE_XRAYED:Wi.NOT_RENDERED;let u=0;u=!i||h?Wi.NOT_RENDERED:n?Wi.EDGES_SELECTED:o?Wi.EDGES_HIGHLIGHTED:r?Wi.EDGES_XRAYED:a?s?Wi.EDGES_COLOR_TRANSPARENT:Wi.EDGES_COLOR_OPAQUE:Wi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Wi.PICK:Wi.NOT_RENDERED)<<12,p|=(t&L?255:0)<<16,hn[0]=p,this._state.flagsBuf.setData(hn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(un[0]=t[0],un[1]=t[1],un[2]=t[2],this._state.offsetsBuf.setData(un,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class dn extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class fn extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class En extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class yn extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class gn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new dn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fn(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 En(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new yn(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const vn={};class In{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const _n=u.vec4(),Tn=u.vec4(),Rn=u.vec4([0,0,0,1]),Pn=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.OBB3();class Dn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=vn[t];return s||(s=new gn(e),vn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete vn[t],s._destroy()}))),s}(e.model.scene),this._buffer=new In(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new He({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,i=e.color,r=e.colorsCompressed,o=e.colors,n=e.meshMatrix,a=e.worldAABB,l=e.pickColor,h=this._buffer,c=h.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=br(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Cn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class Nn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class On extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Sn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class xn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 wn extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Bn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new bn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Cn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new xn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Nn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new On(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Sn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new wn(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Mn={};const Fn=new Uint8Array(4),Ln=new Float32Array(1),Un=u.vec4([0,0,0,1]),Hn=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]);const Gn=new Float32Array(3);class Vn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=Mn[t];return s||(s=new Bn(e),Mn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Mn[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new He({obb:u.OBB3(),numInstances:0,origin:e.origin?u.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=u.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),u.collapseAABB3(s);const r=this._state.obb,o=r.length;for(let e=0;e0){let i=!1;s.flagsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new ge(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=u.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new ge(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;s.pickColorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fn[0]=t[0],Fn[1]=t[1],Fn[2]=t[2],this._state.colorsBuf.setData(Fn,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&B),r=!!(t&H),o=!!(t&G),n=!!(t&V),a=!!(t&k),l=!!(t&F),h=!!(t&M);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Wi.NOT_RENDERED:s?Wi.COLOR_TRANSPARENT:Wi.COLOR_OPAQUE,A=!i||h?Wi.NOT_RENDERED:n?Wi.SILHOUETTE_SELECTED:o?Wi.SILHOUETTE_HIGHLIGHTED:r?Wi.SILHOUETTE_XRAYED:Wi.NOT_RENDERED;let u=0;u=!i||h?Wi.NOT_RENDERED:n?Wi.EDGES_SELECTED:o?Wi.EDGES_HIGHLIGHTED:r?Wi.EDGES_XRAYED:a?s?Wi.EDGES_COLOR_TRANSPARENT:Wi.EDGES_COLOR_OPAQUE:Wi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Wi.PICK:Wi.NOT_RENDERED)<<12,p|=(t&L?255:0)<<16,Ln[0]=p,this._state.flagsBuf.setData(Ln,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Gn[0]=t[0],Gn[1]=t[1],Gn[2]=t[2],this._state.offsetsBuf.setData(Gn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,Wi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,Wi.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class kn{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 jn{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Qn={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={}}};const Wn=new class{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==zn[e])return void zn[e].push({onLoad:t,onProgress:s,onError:i});zn[e]=[],zn[e].push({onLoad:t,onProgress:s,onError:i});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 s=zn[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Qn.add(e,t);const s=zn[e];delete zn[e];for(let e=0,i=s.length;e{const s=zn[e];if(void 0===s)throw this.manager.itemError(e),t;delete zn[e];for(let e=0,i=s.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 Yn{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 i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Xn=0;class Zn{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Yn,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Kn;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new Kn;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=Zn.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(Zn.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Zn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Zn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),Xn>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Xn++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===A?3001:3e3,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Xn--}}Zn.BasisFormat={ETC1S:0,UASTC_4x4:1},Zn.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},Zn.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},Zn.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),E=n.getDFDFlags(),{transcoderFormat:y,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i{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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const o=this._getNextId(),n=new s(o);for(let s=0,o=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new r(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(i);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);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,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let 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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}let a=!0,l=a?Float64Array:Float32Array;const h=new l(16),c=new l(16),A=new l(4),u={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 s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new 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,s){const i=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,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new l(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>u.dotVec4(e,e),lenVec4:e=>Math.sqrt(u.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=>u.dotVec3(e,e),sqLenVec2:e=>u.dotVec2(e,e),lenVec3:e=>Math.sqrt(u.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,s)=>u.lenVec3(u.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(u.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,s)=>u.lenVec2(u.subVec2(t,s,e))})(),rcpVec3:(e,t)=>u.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/u.lenVec4(e);return u.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/u.lenVec3(e);return u.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/u.lenVec2(e);return u.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=u.dotVec3(e,t)/Math.sqrt(u.sqLenVec3(e)*u.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=u.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=u.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=u.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||u.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:()=>u.m4s(0),setMat4ToOnes:()=>u.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,s,i)=>u.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>u.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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>u.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],E=e[14],y=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],D=t[7],b=t[8],C=t[9],N=t[10],O=t[11],S=t[12],x=t[13],w=t[14],B=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*E,s[3]=g*n+v*c+I*d+_*y,s[4]=T*i+R*a+P*A+D*f,s[5]=T*r+R*l+P*u+D*m,s[6]=T*o+R*h+P*p+D*E,s[7]=T*n+R*c+P*d+D*y,s[8]=b*i+C*a+N*A+O*f,s[9]=b*r+C*l+N*u+O*m,s[10]=b*o+C*h+N*p+O*E,s[11]=b*n+C*c+N*d+O*y,s[12]=S*i+x*a+w*A+B*f,s[13]=S*r+x*l+w*u+B*m,s[14]=S*o+x*h+w*p+B*E,s[15]=S*n+x*c+w*d+B*y,s},mulMat3(e,t,s){s||(s=new l(9));const i=e[0],r=e[3],o=e[6],n=e[1],a=e[4],h=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],E=t[4],y=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*E+o*v,s[6]=i*f+r*y+o*I,s[1]=n*p+a*m+h*g,s[4]=n*d+a*E+h*v,s[7]=n*f+a*y+h*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*E+u*v,s[8]=c*f+A*y+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=u.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],E=e[15],y=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,D=c*E-p*d,b=A*m-u*f,C=A*E-p*f,N=u*E-p*m,O=1/(y*N-g*C+v*b+I*D-_*P+T*R);return t[0]=(a*N-l*C+h*b)*O,t[1]=(-i*N+r*C-o*b)*O,t[2]=(f*T-m*_+E*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*N+l*D-h*P)*O,t[5]=(s*N-r*D+o*P)*O,t[6]=(-d*T+m*v-E*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*C-a*D+h*R)*O,t[9]=(-s*C+i*D-o*R)*O,t[10]=(d*_-f*v+E*y)*O,t[11]=(-c*_+A*v-p*y)*O,t[12]=(-n*b+a*P-l*R)*O,t[13]=(s*b-i*P+r*R)*O,t[14]=(-d*I+f*g-m*y)*O,t[15]=(c*I-A*g+u*y)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||u.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||u.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.translationMat4v(e,r))})(),translationMat4s:(e,t)=>u.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>u.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=u.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,p,d,f,m;return c=a*l,A=l*h,p=h*a,d=a*r,f=l*r,m=h*r,(s=s||u.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*p-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*p+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>u.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=u.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=u.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,u.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>u.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=u.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,p=i*h,d=r*l,f=r*h,m=o*h,E=n*a,y=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=p-y,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+E,s[7]=0,s[8]=p+y,s[9]=f-E,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=u.vec4()){const i=u.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],p=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,p),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,p),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,p),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,p),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,p))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,p),s[1]=0)),s},composeMat4:(e,t,s,i=u.mat4())=>(u.quaternionToRotationMat4(t,i),u.scaleMat4v(s,i),u.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=u.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=u.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=u.lenVec3(e);u.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,u.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=u.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],p=t[2];if(r===c&&o===A&&n===p)return u.identityMat4();let d,f,m,E,y,g,v,I,_,T;return d=r-c,f=o-A,m=n-p,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,E=l*m-h*f,y=h*d-a*m,g=a*f-l*d,T=Math.sqrt(E*E+y*y+g*g),T?(T=1/T,E*=T,y*=T,g*=T):(E=0,y=0,g=0),v=f*g-m*y,I=m*E-d*g,_=d*y-f*E,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=E,i[1]=v,i[2]=d,i[3]=0,i[4]=y,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(E*r+y*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>u.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=u.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];u.addVec4(r,i,h),u.subVec4(r,i,c);const o=2*i[2],n=c[0],a=c[1],l=c[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=h[0]/n,s[9]=h[1]/a,s[10]=-h[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=u.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],u.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,s=u.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=u.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],E=e[8],y=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),s=new l(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||u.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||u.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=u.vec4()){const i=e[0]*u.DEGTORAD/2,r=e[1]*u.DEGTORAD/2,o=e[2]*u.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=u.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const p=s+n+c;return p>0?(A=.5/Math.sqrt(p+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=u.vec4()){const i=Math.sqrt(u.dotVec3(e,e)*u.dotVec3(t,t));let r=i+u.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):u.cross3Vec3(e,t,s),s[3]=r,u.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=u.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new l(16);return(t,s,i)=>(i=i||u.vec3(),u.quaternionToRotationMat4(t,e),u.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=u.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=u.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,p=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-p*-a,s[1]=A*h+d*-a+p*-n-c*-l,s[2]=p*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=u.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,p=n*s,d=a*s,f=l*s,m=a*i,E=l*i,y=l*r;return t[0]=1-(m+y),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(p+y),t[6]=E+h,t[8]=f+c,t[9]=E-h,t[10]=1-(p+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,E=o*l;return t[0]=1-(u+d),t[4]=c-E,t[8]=A+m,t[1]=c+E,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=u.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>u.normalizeQuaternion(u.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=u.vec4()){const s=(e=u.normalizeQuaternion(e,A))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,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,s,i)=>new l([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],E=e[9],y=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new l(3),t=new l(3),s=new l(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],u.subVec3(t,e,s),Math.abs(u.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=u.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(u.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||u.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||u.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=u.AABB3())=>(e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MAX_DOUBLE,e[3]=u.MIN_DOUBLE,e[4]=u.MIN_DOUBLE,e[5]=u.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=u.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,s,i)=>{s=s||u.AABB3();let r,o,n,a=u.MAX_DOUBLE,l=u.MAX_DOUBLE,h=u.MAX_DOUBLE,c=u.MIN_DOUBLE,A=u.MIN_DOUBLE,p=u.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>p&&(p=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=p,s}})(),OBB3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=u.AABB3()){let s,i,r,o=u.MAX_DOUBLE,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new l(3);return(t,s)=>{s=s||u.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(s,i)=>{i=i||u.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=u.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=u.vec3()){let s=0,i=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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MIN_DOUBLE,e[3]=u.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=u.AABB2()){let s,i,r,o,n=u.MAX_DOUBLE,a=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+3*e*e*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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=u.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,p=r*l-o*a,d=Math.sqrt(c*c+A*A+p*p);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=p/d),i},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3);return(o,n,a,l,h,c)=>{c=c||u.vec3();const A=u.subVec3(l,a,e),p=u.subVec3(h,a,t),d=u.cross3Vec3(n,p,s),f=u.dotVec3(A,d);if(f<1e-6)return null;const m=u.subVec3(o,a,i),E=u.dotVec3(m,d);if(E<0||E>f)return null;const y=u.cross3Vec3(m,A,r),g=u.dotVec3(n,y);if(g<0||E+g>f)return null;const v=u.dotVec3(p,y)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),s=new l(3),i=new l(3);return(r,o,n,a,l,h)=>{h=h||u.vec3(),o=u.normalizeVec3(o,e);const c=u.subVec3(a,n,t),A=u.subVec3(l,n,s),p=u.cross3Vec3(c,A,i);u.normalizeVec3(p,p);const d=-u.dotVec3(n,p),f=-(u.dotVec3(r,p)+d)/u.dotVec3(o,p);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),s=new l(3);return(i,r,o,n,a)=>{const l=u.subVec3(n,r,e),h=u.subVec3(o,r,t),c=u.subVec3(i,r,s),A=u.dotVec3(l,l),p=u.dotVec3(l,h),d=u.dotVec3(l,c),f=u.dotVec3(h,h),m=u.dotVec3(h,c),E=A*f-p*p;if(0===E)return null;const y=1/E,g=(f*d-p*m)*y,v=(A*m-p*d)*y;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=u.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,E=0;for(f=0,m=e.length;f{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let p,d,f,m,E,y,g;for(h=0,c=a.length;h{const e=new l(3),t=new l(3),s=new l(3),i=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const p=1e4;let d,f,m,E,y,g;for(f=0,E=e.length;f{const e=new l(4),t=new l(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,u.transformVec4(s,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],u.transformVec3(s,e,t),u.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),s=new l(4),i=new l(4),r=new l(4),o=new l(4);return(n,a,l,h,c,A)=>{const p=u.mulMat4(l,a,e),d=u.inverseMat4(p,t),f=n.width,m=n.height,E=(h[0]-f/2)/(f/2),y=-(h[1]-m/2)/(m/2);s[0]=E,s[1]=y,s[2]=-1,s[3]=1,u.transformVec4(d,s,i),u.mulVec4Scalar(i,1/i[3]),r[0]=E,r[1]=y,r[2]=1,r[3]=1,u.transformVec4(d,r,o),u.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],u.subVec3(o,i,A),u.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(s,i,r,o,n,a,l)=>{u.canvasPosToWorldRay(s,i,r,n,e,t),u.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),s=new l(4);return(i,r,o,n,a)=>{const l=u.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],u.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let h,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,h=0,c=s.length;hn[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(s.length<20||o>10)return a.triangles=s,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 p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let E=0;for(h=0,c=s.length;h{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};u.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();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 d=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),i=s+e[1],r=s;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),s=new Uint8Array(e);for(var n=0;n=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}},I={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},_=[];let T,R=0,P=0;const D=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(D.scenes[e.id])return void console.error(`[ERROR] Scene ${E.inQuotes(e.id)} already exists`)}else e.id=g.addItem({});D.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;y[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},p.components.scenes++,e.once("destroyed",(()=>{g.removeItem(e.id),delete D.scenes[e.id],delete y[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in D.scenes)D.scenes.hasOwnProperty(t)&&(e=D.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete D.scenes[e.id]))},this.scheduleTask=function(e,t){v.push(e),v.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;v.length>0&&(e<0||i0&&T>0){var t=1e3/T;P+=t,_.push(t),_.length>=30&&(P-=_.shift()),p.frame.fps=Math.round(P/_.length)}!function(e){const t=D.runTasks(e+10),s=D.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=s,p.frame.tasksBudget=10}(e),function(e){for(var t in I.time=e,D.scenes)if(D.scenes.hasOwnProperty(t)){var s=D.scenes[t];I.sceneId=t,I.startTime=s.startTime,I.deltaTime=null!=I.prevTime?I.time-I.prevTime:0,s.fire("tick",I,!0)}I.prevTime=e}(e),function(){const e=D.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=y[n],i||(i=y[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),R=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(b):requestAnimationFrame(b)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(b):requestAnimationFrame(b);class C{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof C))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],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,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let 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:s,scope:i||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+E.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(E.isNumeric(s)||E.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+E.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+E.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+E.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():D.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(u.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){K.set(this._viewPos),K[3]=1,u.transformPoint4(this.scene.camera.projMatrix,K,Y);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+Y[0]/Y[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-Y[1]/Y[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 z?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]),S(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 Z{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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.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,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class q{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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),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.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 s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class J{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+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 $=u.vec3(),ee=u.vec3();class te extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new X(s,t.origin),this._cornerMarker=new X(s,t.corner),this._targetMarker=new X(s,t.target),this._originWorld=u.vec3(),this._cornerWorld=u.vec3(),this._targetWorld=u.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new Z(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new Z(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new J(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,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=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(u.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){const p=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>p||f>p||m>p)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);u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const E=this._container.getBoundingClientRect();for(var r=i.top-E.top,o=i.left-E.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{switch(e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red"),r=!0,o=e.entity,l.set(e.worldPos),h.set(e.canvasPos),this._mouseState){case 0:this.markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this.markerDiv.style.marginTop=e.canvasPos[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(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,i&&(i.visible=!0,i.centerPos=e.cursorPos,i.cursorPos=e.cursorPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class re extends n{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 ie(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,s=e.corner,i=e.target,r=new te(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.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]})),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,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const ne=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class ae extends C{constructor(e,t={}){super(e,t),this._backgroundColor=u.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new oe(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-"+u.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?he.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?he.FS_MAX_FLOAT_PRECISION="mediump":he.FS_MAX_FLOAT_PRECISION="lowp":he.FS_MAX_FLOAT_PRECISION="mediump",he.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),he.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),he.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),he.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),he.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),he.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),he.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),he.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),he.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),he.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){he.SUPPORTED_EXTENSIONS[e]=!0})))}class Ae{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class ue{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function Ee(e){console.error(e.join("\n"))}class ye{constructor(e,t){this.id=fe.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 ue(e,e.VERTEX_SHADER,me(this.source.vertex)),this._fragmentShader=new ue(e,e.FRAGMENT_SHADER,me(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Ee(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Ee(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Ee(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Ee(this.errors);let t,s,i,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 Ee(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.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 ve{constructor(e,t){this.scene=e,this.aabb=u.AABB3(),this.origin=u.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){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new ve(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new ve(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new ye(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),p=Math.random(),d="perspective"===i.camera.projection;Re[0]=o,Re[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,Re),t.uniform1f(this._uRandomSeed,p);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ye(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const i=new Float32Array([1,1,0,1,0,0,1,0]),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 ge(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new ge(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new ge(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const De=new Float32Array(xe(17,[0,1])),be=new Float32Array(xe(17,[1,0])),Ce=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(Se(i,t));return s}(17,4)),Ne=new Float32Array(2);class Oe{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 ye(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new ge(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new ge(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ge(e,e.ELEMENT_ARRAY_BUFFER,i,i.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Ne[0]=n,Ne[1]=a,i.uniform2fv(this._uViewport,Ne),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,be):i.uniform2fv(this._uSampleOffsets,De),i.uniform1fv(this._uSampleWeights,Ce);const A=e.getDepthTexture(),p=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,p,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Se(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function xe(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class we{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(e=null){if(this._touch(e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(e=null){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=i.createTexture();let o;i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e?i.texStorage2D(i.TEXTURE_2D,1,e,t,s):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,s,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,a),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r,depthTexture:o,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,i=null,r=Uint8Array,o=4){const n=e,a=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,l=new r(o),h=this.gl;return h.readPixels(n,a,1,1,s||h.RGBA,i||h.UNSIGNED_BYTE,l,0),l}readArray(e=null,t=null,s=Uint8Array,i=4){const r=new s(this.buffer.width*this.buffer.height*i),o=this.gl;return o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,r,0),r}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=l.size[0],i=t%s-Math.floor(s/2),o=Math.floor(t/s)-Math.floor(s/2),a=Math.sqrt(Math.pow(i,2)+Math.pow(o,2));y.push({x:i,y:o,dist:a,isVertex:r&&n?d[e+3]>p.length/2:r,result:[d[e+0],d[e+1],d[e+2],d[e+3]]})}let g=null,v=null;if(y.length>0){y.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),v=y[0].isVertex?"vertex":"edge",y=y[0].result;const e=p[y[3]],t=e.origin,s=e.coordinateScale;g=[y[0]*s[0]+t[0],y[1]*s[1]+t[1],y[2]*s[2]+t[2]]}if(null===f&&null==g)return null;let _=null;return null!==g&&(_=t.camera.projectWorldPos(g)),{snapType:v,snappedToVertex:"vertex"===v,snappedToEdge:"edge"===v,worldPos:f,snappedWorldPos:g,snappedCanvasPos:_}},this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Te(t,I),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(),i.reset(),i.backfaces=!0,i.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 h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=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()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=(e,t)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",s,!0)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!0)}))}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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 Ue=new e({});class He{constructor(e){this.id=Ue.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){Ue.removeItem(this.id)}}class Ge extends C{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new He({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],s=e[3];this._state.boundary=[0,0,t,s],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class Ve extends C{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),u.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ke extends C{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),u.orthoMat4c(n,a,h,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class je extends C{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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(){u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Qe extends C{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new He({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.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&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,u.mulMat4v4(this.inverseMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const We=u.vec3(),ze=u.vec3(),Ke=u.vec3(),Ye=u.vec3(),Xe=u.vec3(),Ze=u.vec3(),qe=u.vec4(),Je=u.vec4(),$e=u.vec4(),et=u.mat4(),tt=u.mat4(),st=u.vec3(),it=u.vec3(),rt=u.vec3(),ot=u.vec3();class nt extends C{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new He({deviceMatrix:u.mat4(),hasDeviceMatrix:!1,matrix:u.mat4(),normalMatrix:u.mat4(),inverseMatrix:u.mat4()}),this._perspective=new Ve(this),this._ortho=new ke(this),this._frustum=new je(this),this._customProjection=new Qe(this),this._project=this._perspective,this._eye=u.vec3([0,0,10]),this._look=u.vec3([0,0,0]),this._up=u.vec3([0,1,0]),this._worldUp=u.vec3([0,1,0]),this._worldRight=u.vec3([1,0,0]),this._worldForward=u.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?(u.subVec3(this._eye,this._look,st),u.normalizeVec3(st,it),u.mulVec3Scalar(it,1e3,rt),u.addVec3(this._look,rt,ot),t=ot):t=this._eye,e.hasDeviceMatrix?(u.lookAtMat4v(t,this._look,this._up,tt),u.mulMat4(e.deviceMatrix,tt,e.matrix)):u.lookAtMat4v(t,this._look,this._up,e.matrix),u.inverseMat4(this._state.matrix,this._state.inverseMatrix),u.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=u.subVec3(this._eye,this._look,We);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,et),t=u.transformPoint3(et,t,ze),this.eye=u.addVec3(this._look,t,Ke),this.up=u.transformPoint3(et,this._up,Ye)}orbitPitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._eye,this._look,We);const s=u.cross3Vec3(u.normalizeVec3(t,ze),u.normalizeVec3(this._up,Ke));u.rotationMat4v(.0174532925*e,s,et),t=u.transformPoint3(et,t,Ye),this.up=u.transformPoint3(et,this._up,Xe),this.eye=u.addVec3(t,this._look,Ze)}yaw(e){let t=u.subVec3(this._look,this._eye,We);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,et),t=u.transformPoint3(et,t,ze),this.look=u.addVec3(t,this._eye,Ke),this._gimbalLock&&(this.up=u.transformPoint3(et,this._up,Ye))}pitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._look,this._eye,We);const s=u.cross3Vec3(u.normalizeVec3(t,ze),u.normalizeVec3(this._up,Ke));u.rotationMat4v(.0174532925*e,s,et),this.up=u.transformPoint3(et,this._up,Ze),t=u.transformPoint3(et,t,Ye),this.look=u.addVec3(t,this._eye,Xe)}pan(e){const t=u.subVec3(this._eye,this._look,We),s=[0,0,0];let i;if(0!==e[0]){const r=u.cross3Vec3(u.normalizeVec3(t,[]),u.normalizeVec3(this._up,ze));i=u.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=u.mulVec3Scalar(u.normalizeVec3(this._up,Ke),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=u.mulVec3Scalar(u.normalizeVec3(t,Ye),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=u.addVec3(this._eye,s,Xe),this.look=u.addVec3(this._look,s,Ze)}zoom(e){const t=u.subVec3(this._eye,this._look,We),s=Math.abs(u.lenVec3(t,ze)),i=Math.abs(s+e);if(i<.5)return;const r=u.normalizeVec3(t,Ke);this.eye=u.addVec3(this._look,u.mulVec3Scalar(r,i),Ye)}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=u.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 u.lenVec3(u.subVec3(this._look,this._eye,We))}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=qe,s=Je,i=$e;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,u.mulMat4v4(this.viewMatrix,t,s),u.mulMat4v4(this.projMatrix,s,i),u.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class at extends C{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class lt extends at{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new He({type:"dir",dir:u.vec3([1,1,1]),color:u.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=u.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];u.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=u.identityMat4()),u.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 ht extends at{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:u.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 ct extends C{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var At=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();const ut=function(){const e=u.mat4(),t=u.mat4();return function(s,i){i=i||u.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return u.identityMat4(e),u.translationMat4v(s,e),u.identityMat4(t),u.scalingMat4v([a/c,l/c,h/c],t),u.mulMat4(e,t,i),i}}();var pt=function(){const e=u.mat4(),t=u.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[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[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function mt(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function Et(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const yt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=ft(e,a,"floor","ceil"),i=mt(s),o=Et(e,a,i),o>n&&(r=s,n=o),s=ft(e,a,"ceil","ceil"),i=mt(s),o=Et(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},gt=p.memory,vt=u.AABB3();class It extends ct{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new He({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=yt.getPositionsBounds(t.positions),i=yt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=yt.getUVBounds(t.uv),i=yt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=yt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),gt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),gt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ge(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),gt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new ge(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),gt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ge(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),gt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ge(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),gt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=At(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),gt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=u.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),gt.positions+=this._pickTrianglePositionsBuf.numItems,gt.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),yt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=yt.getPositionsBounds(e),i=yt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),yt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),yt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=u.AABB3()),u.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=u.OBB3()),u.positions3ToAABB3(this._state.positions,vt,this._state.positionsDecodeMatrix),u.AABB3ToOBB3(vt,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(),gt.meshes--}}function _t(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return E.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Tt extends C{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Rt={opaque:0,mask:1,blend:2},Pt=["opaque","mask","blend"];class Dt extends Tt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new He({type:"PhongMaterial",ambient:u.vec3([1,1,1]),diffuse:u.vec3([1,1,1]),specular:u.vec3([1,1,1]),emissive:u.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=Rt[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 Pt[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 bt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Ct extends Tt{get type(){return"EmphasisMaterial"}get presets(){return bt}constructor(e,t={}){super(e,t),this._state=new He({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=bt[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(bt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Nt={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 Ot extends Tt{get type(){return"EdgeMaterial"}get presets(){return Nt}constructor(e,t={}){super(e,t),this._state=new He({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=Nt[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(Nt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const St={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 xt extends C{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=u.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return St}set units(e){e||(e="meters");St[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=u.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=u.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 C{constructor(e,t={}){super(e,t),this._supported=he.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 Bt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Mt extends Tt{get type(){return"PointsMaterial"}get presets(){return Bt}constructor(e,t={}){super(e,t),this._state=new He({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=Bt[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(Bt).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 Ft={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Lt extends Tt{get type(){return"LinesMaterial"}get presets(){return Ft}constructor(e,t={}){super(e,t),this._state=new He({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=Ft[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ft).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ut(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Fe(this,{transparent:i,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,i=t.length;e0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=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 "+E.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=u.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],E.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&D.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=Ut(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=Ut(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t{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=u.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){E.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.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);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.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=s.sectionPlanes.length;e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),A=jt(e),u=i.sectionPlanes.length>0,p=kt(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),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(A){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("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&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(p){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=jt(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=kt(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));p&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Vt[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("}")),(A||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 = "+Vt[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Vt[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Vt[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Vt[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Vt[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){h&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),A&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||A)&&(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 s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class Yt{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.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);"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.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;"));i&&(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=s.sectionPlanes.length;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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Xt=new e({}),Zt=u.vec3(),qt=function(e,t){this.id=Xt.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Yt(t),this._allocate(t)},Jt={};qt.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Jt[t];return s||(s=new qt(t,e),Jt[t]=s,p.memory.programs++),s._useCount++,s},qt.prototype.put=function(){0==--this._useCount&&(Xt.removeItem(this.id),this._program&&this._program.destroy(),delete Jt[this._hash],p.memory.programs--)},qt.prototype.webglContextRestored=function(){this._program=null},qt.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._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),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.sectionPlanes.length>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;"));i&&(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=s.sectionPlanes.length;e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const es=new e({}),ts=u.vec3(),ss=function(e,t){this.id=es.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new $t(t),this._allocate(t)},is={};ss.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=is[t];return s||(s=new ss(t,e),is[t]=s,p.memory.programs++),s._useCount++,s},ss.prototype.put=function(){0==--this._useCount&&(es.removeItem(this.id),this._program&&this._program.destroy(),delete is[this._hash],p.memory.programs--)},ss.prototype.webglContextRestored=function(){this._program=null},ss.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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;"),i){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 os=u.vec3(),ns=function(e,t){this._hash=e,this._shaderSource=new rs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},as={};ns.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=as[t];if(!s){if(s=new ns(t,e),s.errors)return console.log(s.errors.join("\n")),null;as[t]=s,p.memory.programs++}return s._useCount++,s},ns.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete as[this._hash],p.memory.programs--)},ns.prototype.webglContextRestored=function(){this._program=null},ns.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},ns.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ye(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 hs=u.vec3(),cs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ls(t),this._allocate(t)},As={};cs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=As[t];if(!s){if(s=new cs(t,e),s.errors)return console.log(s.errors.join("\n")),null;As[t]=s,p.memory.programs++}return s._useCount++,s},cs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete As[this._hash],p.memory.programs--)},cs.prototype.webglContextRestored=function(){this._program=null},cs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 ps=u.vec3(),ds=function(e,t){this._hash=e,this._shaderSource=new us(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},fs={};ds.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=fs[t];if(!s){if(s=new ds(t,e),s.errors)return console.log(s.errors.join("\n")),null;fs[t]=s,p.memory.programs++}return s._useCount++,s},ds.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete fs[this._hash],p.memory.programs--)},ds.prototype.webglContextRestored=function(){this._program=null},ds.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.sectionPlanes.length>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),i){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 Es=function(e,t){this._hash=e,this._shaderSource=new ms(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ys={};Es.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=ys[s];if(!i){if(i=new Es(s,e),i.errors)return console.log(i.errors.join("\n")),null;ys[s]=i,p.memory.programs++}return i._useCount++,i},Es.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ys[this._hash],p.memory.programs--)},Es.prototype.webglContextRestored=function(){this._program=null},Es.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Es.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ye(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Ss=function(){const e=u.vec3(),t=u.vec3(),s=u.vec3(),i=u.vec3(),r=u.vec3(),o=u.vec3(),n=u.vec4(),a=u.vec3(),l=u.vec3(),h=u.vec3(),c=u.vec3(),A=u.vec3(),p=u.vec3(),d=u.vec3(),f=u.vec3(),m=u.vec3(),E=u.vec4(),y=u.vec4(),g=u.vec4(),v=u.vec3(),I=u.vec3(),_=u.vec3(),T=u.vec3(),R=u.vec3(),P=u.vec3(),D=u.vec3(),b=u.vec3(),C=u.vec3(),N=u.vec3(),S=u.vec3();return function(x,w,B,M){var F=M.primIndex;if(null!=F&&F>-1){const G=x.geometry._state,V=x.scene,k=V.camera,j=V.canvas;if("triangles"===G.primitiveName){M.primitive="triangle";const V=F,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var L=Q[V+0],U=Q[V+1],H=Q[V+2];o[0]=L,o[1]=U,o[2]=H,M.indices=o,z=3*L,K=3*U,Y=3*H}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(yt.decompressPosition(s,e,s),yt.decompressPosition(i,e,i),yt.decompressPosition(r,e,r))}M.canvasPos?u.canvasPosToLocalRay(j.canvas,x.origin?O(w,x.origin):w,B,x.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&u.worldRayToLocalRay(x.worldMatrix,M.origin,M.direction,e,t),u.normalizeVec3(t),u.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,E[0]=n[0],E[1]=n[1],E[2]=n[2],E[3]=1,u.transformVec4(x.worldMatrix,E,y),a[0]=y[0],a[1]=y[1],a[2]=y[2],M.canvasPos&&x.origin&&(a[0]+=x.origin[0],a[1]+=x.origin[1],a[2]+=x.origin[2]),M.worldPos=a,u.transformVec4(k.matrix,y,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,u.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=G.normals;if(X){if(G.compressGeometry){const e=3*L,t=3*U,s=3*H;yt.decompressNormal(X.subarray(e,e+2),c),yt.decompressNormal(X.subarray(t,t+2),A),yt.decompressNormal(X.subarray(s,s+2),p)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],p[0]=X[Y],p[1]=X[Y+1],p[2]=X[Y+2];const e=u.addVec3(u.addVec3(u.mulVec3Scalar(c,h[0],v),u.mulVec3Scalar(A,h[1],I),_),u.mulVec3Scalar(p,h[2],T),R);M.worldNormal=u.normalizeVec3(u.transformVec3(x.worldNormalMatrix,e,P))}const Z=G.uv;if(Z){if(d[0]=Z[2*L],d[1]=Z[2*L+1],f[0]=Z[2*U],f[1]=Z[2*U+1],m[0]=Z[2*H],m[1]=Z[2*H+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(yt.decompressUV(d,e,d),yt.decompressUV(f,e,f),yt.decompressUV(m,e,m))}M.uv=u.addVec3(u.addVec3(u.mulVec2Scalar(d,h[0],D),u.mulVec2Scalar(f,h[1],b),C),u.mulVec2Scalar(m,h[2],N),S)}}}}}();function xs(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],y=[],g=[],v=[];let I,_,T,R,P,D,b,C,N,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,D=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),y.push(P*T),y.push(x),y.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(D+h),m.push(P*R+c);for(I=0;I0){for(N=m.length/3,y.push(0),y.push(1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(t*T),y.push(1),y.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(N=m.length/3,y.push(0),y.push(-1),y.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,y.push(s*T),y.push(-1),y.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Ws(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=Ws(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Ws(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Xs(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Xs(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Ws(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Ws(s,this.magFilter)));const a=Ws(s,this.format,this.encoding),l=Ws(s,this.type),h=Ys(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class $s extends C{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new He({texture:new Ks({gl:this.scene.canvas.gl}),matrix:u.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=u.vec2([0,0]),this._scale=u.vec2([1,1]),this._rotate=u.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 Ks({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=u.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=u.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?u.mulMat4(t,s):s),0!==this._rotate&&(s=u.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?u.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Zs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=Zs(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const ei=p.memory,ti=u.AABB3();class si extends ct{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new He({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=u.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=yt.getPositionsBounds(t.positions),o=yt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new ge(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),ei.positions+=s.positionsBuf.numItems,u.positions3ToAABB3(t.positions,this._aabb),u.positions3ToAABB3(r,ti,s.positionsDecodeMatrix),u.AABB3ToOBB3(ti,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new ge(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),ei.colors+=s.colorsBuf.numItems}if(t.uv){const e=yt.getUVBounds(t.uv),r=yt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new ge(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),ei.uvs+=s.uvBuf.numItems}if(t.normals){const e=yt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new ge(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),ei.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),ei.indices+=s.indicesBuf.numItems;const o=At(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),ei.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(),ei.meshes--}}var ii={};function ri(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,y=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,D,b,C=0,N=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],p=[],d=[];let f,m,y,g,v,I,_,T,R,P,D,b;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),y=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(y+a),c.push(g+l),c.push(v+h),p.push(1-_/i),p.push(T/r),I=u.normalizeVec3(u.subVec3([y,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,D=(i+1)*(T-1)+_,b=(i+1)*T+_,d.push(R),d.push(P),d.push(D),d.push(D),d.push(b),d.push(R);return E.apply(e,{positions:c,normals:A,uv:p,indices:d})}ii.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},ii.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(ii.parse._buffToStr(e));window.location.href=s},ii.clone=function(e){return JSON.parse(JSON.stringify(e))},ii.bin={},ii.bin.f=new Float32Array(1),ii.bin.fb=new Uint8Array(ii.bin.f.buffer),ii.bin.rf=function(e,t){for(var s=ii.bin.f,i=ii.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},ii.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},ii.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},ii.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},ii.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},ii.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},ii.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},ii.parse={},ii.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class ni extends C{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=u.vec3(t.pos||[0,0,0]),this._up=u.vec3(t.up||[0,1,0]),this._normal=u.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=u.vec3(),this._rtcPos=u.vec3(),this._imageSize=u.vec2(),this._texture=new $s(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 Qs(this,{matrix:u.inverseMat4(u.lookAtMat4v(this._pos,u.subVec3(this._pos,this._normal,u.mat4()),this._up,u.mat4())),children:[this._bitmapMesh=new Os(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new It(this,ri({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Dt(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 ai=u.vec3(),li=u.vec3(),hi=u.mat4();class ci{constructor(){this.normal=u.vec3(),this.offset=0,this.testVertex=u.vec3()}set(e,t,s,i){const r=1/Math.sqrt(e*e+t*t+s*s);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=s*r,this.offset=i*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class Ai{constructor(){this.planes=[new ci,new ci,new ci,new ci,new ci,new ci]}}function ui(e,t){let s=Ai.INSIDE;const i=ai,r=li;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return Ai.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=Ai.INTERSECT)}return s}Ai.INSIDE=0,Ai.INTERSECT=1,Ai.OUTSIDE=2;class pi extends C{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=u.vec3(),r=x(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,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}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),y=Object.entries(E).map((([e,t])=>({color:e,components:t})));o.components.coloring=y;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=vi(e.location,di),s=vi(e.direction,di);h&&u.negateVec3(s),u.subVec3(t,l),r.yUp&&(t=_i(t),s=_i(s)),new Bs(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];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),s.push(r++),s.push(r++))})),new pi(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=vi(e.location,fi),n=vi(e.normal,mi),a=vi(e.up,Ei),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=_i(o),n=_i(n),a=_i(a)),new ni(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.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&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!1),r.space_boundaries_visible)}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const 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((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=vi(e.perspective_camera.camera_view_point,di),h=vi(e.perspective_camera.camera_direction,di),c=vi(e.perspective_camera.camera_up_vector,di),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=vi(e.orthogonal_camera.camera_view_point,di),h=vi(e.orthogonal_camera.camera_direction,di),c=vi(e.orthogonal_camera.camera_up_vector,di),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),u.subVec3(a,l),r.yUp&&(a=_i(a),h=_i(h),c=_i(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:u.addVec3(a,h,di)}else h=u.addVec3(a,h,di);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.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 s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=u.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function gi(e){return{x:e[0],y:e[1],z:e[2]}}function vi(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ii(e){return new Float64Array([e[0],-e[2],e[1]])}function _i(e){return new Float64Array([e[0],e[2],-e[1]])}const Ti=u.vec3(),Ri=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class Pi extends C{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new X(s,t.origin),this._targetMarker=new X(s,t.target),this._originWorld=u.vec3(),this._targetWorld=u.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 i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new q(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new Z(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new Z(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new Z(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new Z(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new J(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new J(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new J(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new J(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;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&&(u.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);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){u.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=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,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,E=s.unitsInfo[m].abbrev;for(var p=0,d=i.length;p{r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this._markerDiv.style.marginTop=e.canvasPos[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red")):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.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.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null)}destroy(){this.deactivate(),super.destroy()}}class Ci extends n{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._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 bi(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,s=e.target,i=new Pi(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.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,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}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,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(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,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=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),i=!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 Oi{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const i=Si(e,s);return i?t?xi(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=Si(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=xi(r,[t]),s&&(r=xi(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[t];i||(i={},this._eventSubs[t]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function Si(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?Ui._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(u.subVec3(i.eye,i.look,Li),i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Mi),i.look=u.subVec3(Mi,Li,Bi)):this._flyingLook&&(i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Bi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Fi)):this._flyingEyeLookUp&&(i.eye=u.lerpVec3(s,0,1,this._eye1,this._eye2,Mi),i.look=u.lerpVec3(s,0,1,this._look1,this._look2,Bi),i.up=u.lerpVec3(s,0,1,this._up1,this._up2,Fi)),this._projection2){const t="ortho"===this._projection2?Ui._easeOutExpo(e,0,1,1):Ui._easeInCubic(e,0,1,1);i.customProjection.matrix=u.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();D.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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 Hi extends C{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Ui(this),this._t=0,this.state=Hi.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case Hi.SCRUBBING:return;case Hi.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=Hi.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Hi.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=Hi.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=Hi.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=Hi.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=Hi.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=Hi.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Hi.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Hi.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Hi.STOPPED=0,Hi.SCRUBBING=1,Hi.PLAYING=2,Hi.PLAYING_TO=3,u.vec3(),u.vec3(),u.vec3(),u.vec3([0,-1,0]),u.vec4([0,0,0,1]);const Gi=u.vec3();class Vi{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,s){this.numObjects=0,this._mask=s?E.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const n=t._sectionPlanesState.sectionPlanes,a=r*o,l=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;Yi[0]=s,Yi[1]=i,Yi[2]=t.blendCutoff,Yi[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,Yi),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===Wi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Wi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===Wi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?Ki:zi)}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 $i extends Ji{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class er extends $i{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class tr extends Ji{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class sr extends tr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class ir extends Ji{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class rr extends Ji{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class or extends Ji{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class nr extends Ji{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class ar extends $i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class lr extends $i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.sectionPlanes.length>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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 cr extends er{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class Ar extends er{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class ur extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class pr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class dr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class fr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class mr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class Er extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class yr extends $i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class gr extends $i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class Ir extends $i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.sectionPlanes.length>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=i.sectionPlanes.length;e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;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=s.lights.length;e5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Pr=u.mat4(),Dr=u.mat4();function br(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,p=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function Or(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const Sr=u.vec3(),xr=u.vec3(),wr=u.vec3(),Br=u.vec3(),Mr=u.mat4();class Fr extends Ji{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Sr;let m,E;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=xr;if(l){const e=wr;u.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=O(d,t,Mr),E=Br,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Lr=u.vec3(),Ur=u.vec3(),Hr=u.vec3(),Gr=u.vec3(),Vr=u.mat4();class kr extends Ji{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Lr;let m,E;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=Ur;if(l){const e=Hr;u.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=O(d,t,Vr),E=Gr,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class jr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Fr(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new kr(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Fr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new kr(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Qr={};const Wr=u.mat4(),zr=u.mat4(),Kr=u.vec4([0,0,0,1]),Yr=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.OBB3();const Xr=u.vec3(),Zr=u.vec3(),qr=u.vec3(),Jr=u.vec3(),$r=u.vec3(),eo=u.vec3(),to=u.vec3();class so{constructor(e){console.info("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Tr[t];return s||(s=new _r(e),Tr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Tr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=Qr[t];return s||(s=new jr(e),Qr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Qr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Rr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new He({origin:u.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=u.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=u.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=u.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=u.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)for(let e=0,t=r.length;e0){const e=Wr;m?u.inverseMat4(u.transposeMat4(m,zr),e):u.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,p=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=Nr(d,"floor","ceil"),a=Or(n),h=o(d,a),h>c&&(l=n,c=h),n=Nr(d,"ceil","ceil"),a=Or(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,i,i.length,v.normals,v.normals.length)}if(a)for(let e=0,t=a.length;e0)for(let e=0,t=o.length;e0)for(let e=0,t=n.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):br(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=u.mat4());if(e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new ge(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new ge(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=yt.getUVBounds(s.uv),r=yt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=u.mat3(r.decodeMatrix),e.uvBuf=new ge(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new ge(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,i,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;ey)&&(y=e,i.set(g),r&&u.triangleNormal(d,f,m,r),E=!0)}}return E&&r&&(u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),E}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 io extends tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class ro extends tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,r;const o=t.sectionPlanes.length>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,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class no extends sr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class ao extends sr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class lo extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class ho extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class co extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class Ao extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class uo extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 po extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class fo extends tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const mo={3e3:"linearToLinear",3001:"sRGBToLinear"};class Eo extends tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),i.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 = "+mo[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+mo[i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${u.MAX_INT}), 1.0);`),i.push("}"),i}}class go extends tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.sectionPlanes.length>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=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Co=u.vec3(),No=u.vec3(),Oo=u.vec3(),So=u.vec3(),xo=u.mat4();class wo extends Ji{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Co;let m,E;if(f[0]=u.safeInv(p[3]-p[0])*u.MAX_INT,f[1]=u.safeInv(p[4]-p[1])*u.MAX_INT,f[2]=u.safeInv(p[5]-p[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(f[0]),e.snapPickCoordinateScale[1]=u.safeInv(f[1]),e.snapPickCoordinateScale[2]=u.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=No;if(l){const e=u.transformPoint3(c,l,Oo);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=O(d,t,xo),E=So,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Bo{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new bo(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new wo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new bo(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new wo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Mo={};const Fo=new Uint8Array(4),Lo=new Float32Array(1),Uo=u.vec4([0,0,0,1]),Ho=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]);const Go=new Float32Array(3),Vo=u.vec3(),ko=u.vec3(),jo=u.vec3(),Qo=u.vec3(),Wo=u.vec3(),zo=u.vec3(),Ko=u.vec3();class Yo{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Io[t];return s||(s=new vo(e),Io[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Io[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=Mo[t];return s||(s=new Bo(e),Mo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Mo[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new He({numInstances:0,obb:u.OBB3(),origin:u.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf: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._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=u.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,i=e.roughness,r=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,o=e.meshMatrix,n=e.aabb,a=e.pickColor;if(this._finalized)throw"Already finalized";const l=t[0],h=t[1],c=t[2];if(this._colors.push(l),this._colors.push(h),this._colors.push(c),this._colors.push(r),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=i?i:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(o[0]),this._modelMatrixCol0.push(o[4]),this._modelMatrixCol0.push(o[8]),this._modelMatrixCol0.push(o[12]),this._modelMatrixCol1.push(o[1]),this._modelMatrixCol1.push(o[5]),this._modelMatrixCol1.push(o[9]),this._modelMatrixCol1.push(o[13]),this._modelMatrixCol2.push(o[2]),this._modelMatrixCol2.push(o[6]),this._modelMatrixCol2.push(o[10]),this._modelMatrixCol2.push(o[14]),this._state.geometry.normals){let e=u.transposeMat4(o,u.mat4()),t=u.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]);const A=this._state.geometry.positionsCompressed.length,p=this._state.geometry.positionsCompressed,d=this._state.geometry.positionsDecodeMatrix;for(let e=0;e0){let t=!1;e.colorsBuf=new ge(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new ge(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new ge(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new ge(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=u.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new ge(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new ge(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new ge(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new ge(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new ge(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fo[0]=t[0],Fo[1]=t[1],Fo[2]=t[2],Fo[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Fo,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&B),r=!!(t&H),o=!!(t&G),n=!!(t&V),a=!!(t&k),l=!!(t&F),h=!!(t&M);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Wi.NOT_RENDERED:s?Wi.COLOR_TRANSPARENT:Wi.COLOR_OPAQUE,A=!i||h?Wi.NOT_RENDERED:n?Wi.SILHOUETTE_SELECTED:o?Wi.SILHOUETTE_HIGHLIGHTED:r?Wi.SILHOUETTE_XRAYED:Wi.NOT_RENDERED;let u=0;u=!i||h?Wi.NOT_RENDERED:n?Wi.EDGES_SELECTED:o?Wi.EDGES_HIGHLIGHTED:r?Wi.EDGES_XRAYED:a?s?Wi.EDGES_COLOR_TRANSPARENT:Wi.EDGES_COLOR_OPAQUE:Wi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Wi.PICK:Wi.NOT_RENDERED)<<12,p|=(t&L?1:0)<<16,Lo[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(Lo,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Go[0]=t[0],Go[1]=t[1],Go[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Go,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=Uo,p=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&u.triangleNormal(f,m,E,r),y=!0)}}return y&&r&&(u.transformVec3(a.normalMatrix,r,r),u.transformVec3(this.model.worldNormalMatrix,r,r),u.normalizeVec3(r)),y}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 Xo extends or{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Zo extends or{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class qo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Xo(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Zo(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Jo={};class $o{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const en=u.vec4([0,0,0,1]),tn=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.OBB3();class sn{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Jo[t];return s||(s=new qo(e),Jo[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Jo[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new $o(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new He({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=br(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ge(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 on extends nr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class nn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new rn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new on(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const an={};const ln=new Uint8Array(4),hn=new Float32Array(1),cn=u.vec4([0,0,0,1]),An=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]);const un=new Float32Array(3);class pn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=an[t];return s||(s=new nn(e),an[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete an[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new He({obb:u.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=u.vec3(e.origin)),this._finalized=!1,this.aabb=u.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,i=e.meshMatrix,r=e.aabb;if(this._finalized)throw"Already finalized";const o=t[0],n=t[1],a=t[2];t[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),u.collapseAABB3(r);const l=this._state.obb,h=l.length;for(let e=0;e0){let t=!1;this._state.colorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";ln[0]=t[0],ln[1]=t[1],ln[2]=t[2],ln[3]=t[3],this._state.colorsBuf.setData(ln,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&B),r=!!(t&H),o=!!(t&G),n=!!(t&V),a=!!(t&k),l=!!(t&F),h=!!(t&M);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Wi.NOT_RENDERED:s?Wi.COLOR_TRANSPARENT:Wi.COLOR_OPAQUE,A=!i||h?Wi.NOT_RENDERED:n?Wi.SILHOUETTE_SELECTED:o?Wi.SILHOUETTE_HIGHLIGHTED:r?Wi.SILHOUETTE_XRAYED:Wi.NOT_RENDERED;let u=0;u=!i||h?Wi.NOT_RENDERED:n?Wi.EDGES_SELECTED:o?Wi.EDGES_HIGHLIGHTED:r?Wi.EDGES_XRAYED:a?s?Wi.EDGES_COLOR_TRANSPARENT:Wi.EDGES_COLOR_OPAQUE:Wi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Wi.PICK:Wi.NOT_RENDERED)<<12,p|=(t&L?255:0)<<16,hn[0]=p,this._state.flagsBuf.setData(hn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(un[0]=t[0],un[1]=t[1],un[2]=t[2],this._state.offsetsBuf.setData(un,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class dn extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class fn extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class En extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class yn extends ir{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class gn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new dn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fn(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 En(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new yn(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const vn={};class In{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const _n=u.vec4(),Tn=u.vec4(),Rn=u.vec4([0,0,0,1]),Pn=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]),u.OBB3();class Dn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=vn[t];return s||(s=new gn(e),vn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete vn[t],s._destroy()}))),s}(e.model.scene),this._buffer=new In(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new He({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:u.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=u.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=u.vec3(e.origin)),this.aabb=u.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,i=e.color,r=e.colorsCompressed,o=e.colors,n=e.meshMatrix,a=e.worldAABB,l=e.pickColor,h=this._buffer,c=h.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=br(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ge(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new ge(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ge(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ge(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Cn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class Nn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class On extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Sn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class xn extends rr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 wn extends rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Bn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new bn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Cn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new xn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Nn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new On(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Sn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new wn(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Mn={};const Fn=new Uint8Array(4),Ln=new Float32Array(1),Un=u.vec4([0,0,0,1]),Hn=u.vec4([0,0,0,1]);u.vec4([0,0,0,1]);const Gn=new Float32Array(3);class Vn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=Mn[t];return s||(s=new Bn(e),Mn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Mn[t],s._destroy()}))),s}(e.model.scene),this._aabb=u.collapseAABB3(),this._state=new He({obb:u.OBB3(),numInstances:0,origin:e.origin?u.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=u.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),u.collapseAABB3(s);const r=this._state.obb,o=r.length;for(let e=0;e0){let i=!1;s.flagsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new ge(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=u.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new ge(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new ge(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;s.pickColorsBuf=new ge(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fn[0]=t[0],Fn[1]=t[1],Fn[2]=t[2],this._state.colorsBuf.setData(Fn,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&B),r=!!(t&H),o=!!(t&G),n=!!(t&V),a=!!(t&k),l=!!(t&F),h=!!(t&M);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Wi.NOT_RENDERED:s?Wi.COLOR_TRANSPARENT:Wi.COLOR_OPAQUE,A=!i||h?Wi.NOT_RENDERED:n?Wi.SILHOUETTE_SELECTED:o?Wi.SILHOUETTE_HIGHLIGHTED:r?Wi.SILHOUETTE_XRAYED:Wi.NOT_RENDERED;let u=0;u=!i||h?Wi.NOT_RENDERED:n?Wi.EDGES_SELECTED:o?Wi.EDGES_HIGHLIGHTED:r?Wi.EDGES_XRAYED:a?s?Wi.EDGES_COLOR_TRANSPARENT:Wi.EDGES_COLOR_OPAQUE:Wi.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?Wi.PICK:Wi.NOT_RENDERED)<<12,p|=(t&L?255:0)<<16,Ln[0]=p,this._state.flagsBuf.setData(Ln,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Gn[0]=t[0],Gn[1]=t[1],Gn[2]=t[2],this._state.offsetsBuf.setData(Gn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,Wi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,Wi.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class kn{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 jn{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Qn={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={}}};const Wn=new class{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==zn[e])return void zn[e].push({onLoad:t,onProgress:s,onError:i});zn[e]=[],zn[e].push({onLoad:t,onProgress:s,onError:i});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 s=zn[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{Qn.add(e,t);const s=zn[e];delete zn[e];for(let e=0,i=s.length;e{const s=zn[e];if(void 0===s)throw this.manager.itemError(e),t;delete zn[e];for(let e=0,i=s.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 Yn{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 i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Xn=0;class Zn{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Yn,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Kn;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new Kn;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=Zn.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(Zn.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Zn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Zn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),Xn>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Xn++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===A?3001:3e3,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Xn--}}Zn.BasisFormat={ETC1S:0,UASTC_4x4:1},Zn.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},Zn.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},Zn.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),E=n.getDFDFlags(),{transcoderFormat:y,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i>t;s.sort(ia);const i=new Int32Array(e.length);for(let t=0,r=s.length;te[t+1]){let s=e[t];e[t]=e[t+1],e[t+1]=s}ra=new Int32Array(e),t.sort(oa);const s=new Int32Array(e.length);for(let i=0,r=t.length;it){let s=e;e=t,t=s}function s(s,i){return s!==e?e-s:i!==t?t-i:0}let i=0,r=(o.length>>1)-1;for(;i<=r;){const e=r+i>>1,t=s(o[2*e],o[2*e+1]);if(t>0)i=e+1;else{if(!(t<0))return e;r=e-1}}return-i-1}const a=new Int32Array(o.length/2);a.fill(0);const l=i.length/3;if(l>8*(1<u.maxNumPositions&&(u=A()),u.bucketNumber>8)return[e];let d;-1===h[l]&&(h[l]=u.numPositions++,u.positionsCompressed.push(i[3*l]),u.positionsCompressed.push(i[3*l+1]),u.positionsCompressed.push(i[3*l+2])),-1===h[c]&&(h[c]=u.numPositions++,u.positionsCompressed.push(i[3*c]),u.positionsCompressed.push(i[3*c+1]),u.positionsCompressed.push(i[3*c+2])),-1===h[p]&&(h[p]=u.numPositions++,u.positionsCompressed.push(i[3*p]),u.positionsCompressed.push(i[3*p+1]),u.positionsCompressed.push(i[3*p+2])),u.indices.push(h[l]),u.indices.push(h[c]),u.indices.push(h[p]),(d=n(l,c))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(l,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(c,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]]))}const p=t/8*2,d=t/8,f=2*i.length+(r.length+o.length)*p;let m=0,E=-i.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*d,E+=e.positionsCompressed.length/3})),m>f?[e]:(s&&function(e,t){const s={};let i=0;e.forEach((e=>{const t=e.indices,r=e.edgeIndices,o=e.positionsCompressed;for(let e=0,i=t.length;e0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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,s=e._lightsState;if(this._program=new ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=s.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 sceneModelWorldMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),o.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),o.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform highp sampler2D uTextureModelMatrices;"),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=s.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, 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 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, 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*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),o.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),o.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),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=s.lights.length;e0,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"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const da=new Float32Array([1,1,1]),fa=u.vec3(),ma=u.vec3(),Ea=u.vec3(),ya=u.vec3(),ga=u.mat4();class va{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=fa;if(h){const t=ma;u.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,ga),m=Ea,m[0]=r.eye[0]-e[0],m[1]=r.eye[1]-e[1],m[2]=r.eye[2]-e[2]}else f=d,m=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),s===Wi.SILHOUETTE_XRAYED){const e=i.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.SILHOUETTE_HIGHLIGHTED){const e=i.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.SILHOUETTE_SELECTED){const e=i.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,da);if(i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const E=i._sectionPlanesState.sectionPlanes.length;if(E>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.y) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 Ia=new Float32Array([0,0,0,1]),_a=u.vec3(),Ta=u.vec3(),Ra=u.vec3(),Pa=u.mat4();class Da{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=_a;if(m){const t=u.transformPoint3(A,h,Ta);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,Pa)}else f=d;if(n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),s===Wi.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,Ia);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 ba=u.vec3(),Ca=u.vec3(),Na=u.vec3(),Oa=u.mat4();class Sa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=ba;if(m){const t=u.transformPoint3(A,h,Ca);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,Oa)}else f=d;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureEdgesColorRenderer"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled,s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push(" vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vec4 rgb = vec4(color.rgba);"),s.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 xa=u.vec3(),wa=u.vec3(),Ba=u.vec3(),Ma=u.mat4();class Fa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i;let d,f;l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=xa;if(m){const t=u.transformPoint3(A,h,wa);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=O(o.viewMatrix,e,Ma),f=Ba,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("smooth out vec4 vWorldPosition;"),s.push("flat out uvec4 vFlags2;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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=u.vec3(),Ua=u.vec3(),Ha=u.vec3(),Ga=u.vec3(),Va=u.mat4();class ka{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=e.pickViewMatrix||o.viewMatrix;let f,m;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const t=La;if(h){const e=Ua;u.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],f=O(d,t,Va),m=Ha,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),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._uWorldMatrix,!1,p),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 E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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 ja=u.vec3(),Qa=u.vec3(),Wa=u.vec3(),za=u.vec3(),Ka=u.vec3(),Ya=u.mat4();class Xa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=ja;let E,y;m[0]=u.safeInv(d[3]-d[0])*u.MAX_INT,m[1]=u.safeInv(d[4]-d[1])*u.MAX_INT,m[2]=u.safeInv(d[5]-d[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(m[0]),e.snapPickCoordinateScale[1]=u.safeInv(m[1]),e.snapPickCoordinateScale[2]=u.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=Qa;if(g){const e=u.transformPoint3(A,h,Wa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],E=O(f,t,Ya),y=za,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(_,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(_,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(_,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uSnapVectorA;"),s.push("uniform vec2 uSnapInvVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),s.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Za=u.vec3(),qa=u.vec3(),Ja=u.vec3(),$a=u.vec3(),el=u.vec3(),tl=u.mat4();class sl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=Za;let E,y;m[0]=u.safeInv(d[3]-d[0])*u.MAX_INT,m[1]=u.safeInv(d[4]-d[1])*u.MAX_INT,m[2]=u.safeInv(d[5]-d[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(m[0]),e.snapPickCoordinateScale[1]=u.safeInv(m[1]),e.snapPickCoordinateScale[2]=u.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=qa;if(g){const e=Ja;u.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],E=O(f,t,tl),y=$a,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uVectorAB;"),s.push("uniform vec2 uInverseVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),s.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" } else {"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const il=u.vec3(),rl=u.vec3(),ol=u.vec3(),nl=u.vec3(),al=u.mat4();class ll{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=il;if(h){const t=rl;u.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,al),m=ol,m[0]=o.eye[0]-e[0],m[1]=o.eye[1]-e[1],m[2]=o.eye[2]-e[2]}else f=d,m=o.eye;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" } else {"),s.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const hl=u.vec3(),cl=u.vec3(),Al=u.vec3(),ul=u.vec3(),pl=u.mat4();class dl{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=hl;if(m){const t=u.transformPoint3(A,h,cl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=O(r.viewMatrix,e,pl),f=Al,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),s&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 fl=u.vec3(),ml=u.vec3(),El=u.vec3(),yl=u.vec3(),gl=u.mat4();class vl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const m=0!==l[0]||0!==l[1]||0!==l[2],E=0!==h[0]||0!==h[1]||0!==h[2];if(m||E){const e=fl;if(m){const t=ml;u.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],d=O(p,e,gl),f=El,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=p,f=o.eye;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,A),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,i.worldNormalMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;t0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&he.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec3 normal;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 worldNormalMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 viewNormalMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),he.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(he.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&he.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&&he.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let e=0;e 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&&he.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 Il=u.vec3(),_l=u.vec3(),Tl=u.vec3(),Rl=u.vec3();u.vec4();const Pl=u.mat4();class Dl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=Il;if(m){const t=u.transformPoint3(A,h,_l);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=O(r.viewMatrix,e,Pl),f=Tl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("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;"),s&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),s&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;"),s){i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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(${u.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class bl{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._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=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 va(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Fa(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ka(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Dl(this._scene)),this._vertexDepthRenderer||(this._vertexDepthRenderer=new Xa(this._scene)),this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sl(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 va(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new dl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new vl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Da(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Sa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fa(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Dl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Dl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ka(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new Xa(this._scene)),this._vertexDepthRenderer}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sl(this._scene)),this._snapDepthBufInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ll(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._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Cl={};class Nl{constructor(){this.positionsCompressed=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Ol{constructor(){this.texturePerObjectIdColorsAndFlags=null,this.texturePerObjectIdOffsets=null,this.texturePerObjectIdPositionsDecodeMatrix=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,s,i,r,o){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,s,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,i,3),this.texturePerObjectIdOffsets.bindTexture(e,o,4)}bindTriangleIndicesTextures(e,t,s,i){this.indicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.indicesPerBitnessTextures[i].bindTexture(e,s,6)}bindEdgeIndicesTextures(e,t,s,i){this.edgeIndicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[i].bindTexture(e,s,6)}}class Sl{constructor(e,t,s,i,r=null){this._gl=e,this._texture=t,this._textureWidth=s,this._textureHeight=i,this._textureData=r}bindTexture(e,t,s){return e.bindTexture(t,this,s)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const xl={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(xl,null,4));let e=0;Object.keys(xl).forEach((t=>{t.startsWith("size")&&(e+=xl[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/xl.totalPolygons).toFixed(2)}`);let t={};Object.keys(xl).forEach((s=>{s.startsWith("size")&&(t[s]=`${(xl[s]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class wl{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,s,i,r,o,n){const a=t.length;this.numPortions=a;const l=4096,h=Math.ceil(a/512);if(0===h)throw"texture height===0";const c=new Uint8Array(16384*h);xl.sizeDataColorsAndFlags+=c.byteLength,xl.numberOfTextures++;for(let e=0;e>24&255,i[e]>>16&255,i[e]>>8&255,255&i[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,h),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,h,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Sl(e,A,l,h,c)}generateTextureForObjectOffsets(e,t){const s=512,i=Math.ceil(t/s);if(0===i)throw"texture height===0";const r=new Float32Array(1536*i).fill(0);xl.sizeDataTextureOffsets+=r.byteLength,xl.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,s,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,i,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 Sl(e,o,s,i,r)}generateTextureForPositionsDecodeMatrices(e,t,s){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const r=2048,o=Math.ceil(i/512),n=new Float32Array(8192*o);xl.sizeDataPositionDecodeMatrices+=n.byteLength,xl.numberOfTextures++;const a=u.mat4();for(let e=0;e{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Cl[t],s._destroy()}))),s}(e.scene),this.model=e,this._buffer=new Nl,this._dataTextureState=new Ol,this._dataTextureGenerator=new wl,this._state=new He({origin:u.vec3(t.origin),metallicRoughnessBuf:null,positionsDecodeMatrix:u.mat4(),textureState:this._dataTextureState,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.aabb=u.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&xl.cannotCreatePortion.because10BitsObjectId++;let s=this._numPortions+t<=65536;const i=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[i]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let i=0,r=0;e.buckets.forEach((e=>{i+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+i>16777216||t+r>16777216)&&xl.cannotCreatePortion.becauseTextureSize++,s&&=this._state.numVertices+i<=16777216&&t+r<=16777216}return s}createPortion(e){if(this._finalized)throw"Already finalized";const t=[],s=e.worldAABB;e.buckets.forEach(((i,r)=>{const o=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#${r}`:`${e.id}#${r}`;let n=this._bucketGeometries[o];n||(n=this._createBucketGeometry(e,i),this._bucketGeometries[o]=n);const a=u.collapseAABB3(Ul),l=this._createSubPortion(e,n,i,a);u.expandAABB3(s,a),t.push(l)}));const i=this._state.origin;0===i[0]&&0===i[1]&&0===i[2]||(s[0]+=i[0],s[1]+=i[1],s[2]+=i[2],s[3]+=i[0],s[4]+=i[1],s[5]+=i[2]),u.expandAABB3(this.aabb,s);const r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(t),this.model.numPortions++,r}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;xl.overheadSizeAlignementIndices+=2*(e-t.indices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;xl.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.edgeIndices),t.edgeIndices=s}const s=t.positionsCompressed,i=t.indices,r=t.edgeIndices,o=this._buffer,n=o.positionsCompressed.length/3,a=s.length/3;for(let e=0,t=s.length;e0){let e,s=3*t.numTriangles;t.numVertices<=256?(e=h.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=s,xl.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=h.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=s,xl.totalPolygons16Bits+=t.numTriangles):(e=h.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=s,xl.totalPolygons32Bits+=t.numTriangles),xl.totalPolygons+=t.numTriangles;for(let s=0;s0){let e,s=2*t.numEdges;t.numVertices<=256?(e=h.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=s,xl.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=h.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=s,xl.totalEdges16Bits+=t.numEdges):(e=h.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=s,xl.totalEdges32Bits+=t.numEdges),xl.totalEdges+=t.numEdges;for(let s=0;s0&&(t.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId8Bits)),i.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId16Bits)),i.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId32Bits)),i.indices8Bits.length>0&&(t.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,i.indices8Bits)),i.indices16Bits.length>0&&(t.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,i.indices16Bits)),i.indices32Bits.length>0&&(t.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,i.indices32Bits)),i.edgeIndices8Bits.length>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(s,i.edgeIndices8Bits)),i.edgeIndices16Bits.length>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(s,i.edgeIndices16Bits)),i.edgeIndices32Bits.length>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(s,i.edgeIndices32Bits)),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,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(console.info("_uploadDeferredFlags"),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.texturePerObjectIdColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdColorsAndFlags._textureWidth,t.texturePerObjectIdColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectIdColorsAndFlags._textureData),e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdOffsets._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdOffsets._textureWidth,t.texturePerObjectIdOffsets._textureHeight,e.RGB,e.FLOAT,t.texturePerObjectIdOffsets._textureData)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdColorsAndFlags._texture),i.texSubImage2D(i.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,i.RGBA_INTEGER,i.UNSIGNED_BYTE,Fl)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,i=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),d.bindTexture(d.TEXTURE_2D,p.texturePerObjectIdColorsAndFlags._texture),d.texSubImage2D(d.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,d.RGBA_INTEGER,d.UNSIGNED_BYTE,Fl))}_setDeferredFlags(){}_setFlags2(e,t,s=!1){const i=this._portionToSubPortionsMap[e];for(let e=0,r=i.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectIdColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Fl))}_setDeferredFlags2(){}setOffset(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdOffsets._texture),i.texSubImage2D(i.TEXTURE_2D,0,0,e,1,1,i.RGB,i.FLOAT,Ll))}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._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,Wi.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,Wi.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._dataTextureRenderers.depthRenderer&&this._dataTextureRenderers.depthRenderer.drawLayer(t,this,Wi.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._dataTextureRenderers.normalsRenderer&&this._dataTextureRenderers.normalsRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,Wi.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._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,Wi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,Wi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,Wi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,Wi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,Wi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.occlusionRenderer&&this._dataTextureRenderers.occlusionRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.shadowRenderer&&this._dataTextureRenderers.shadowRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,Wi.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,Wi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,Wi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,Wi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,Wi.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}}const kl=u.vec3();u.mat4();const jl=u.vec3([1,1,1]),Ql=u.vec3([0,0,0]),Wl=u.vec3([0,0,0]),zl=u.identityQuaternion(),Kl=u.identityMat4(),Yl=new Uint8Array([255,255,255]);class Xl extends C{constructor(e,t={}){super(e,t),this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!0,this._vboBatchingLayerScratchMemory=(Qi++,ji),this._textureTranscoder=t.textureTranscoder||function(e){const t=e.scene.id;let s=qn[t];return s||(s=new Zn({viewer:e}),qn[t]=s,e.scene.on("destroyed",(()=>{delete qn[t],s.destroy()}))),s}(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=u.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._entityList=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this._scheduledMeshes={},this.renderFlags=new gs,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._edgeThreshold=t.edgeThreshold||10,this._origin=u.vec3(t.origin||[0,0,0]),this._position=u.vec3(t.position||[0,0,0]),this._rotation=u.vec3(t.rotation||[0,0,0]),this._quaternion=u.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=u.vec4(t.quaternion||[0,0,0,1]),t.rotation&&u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=u.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=u.mat4(),this._worldRotationMatrixConjugate=u.mat4(),this._matrix=u.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=u.mat4(),u.inverseMat4(this._matrix,this._worldNormalMatrix),u.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=u.mat4(),this._viewNormalMatrix=u.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._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}_createDefaultTextureSet(){const e=new jn({id:"defaultColorTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new jn({id:"defaultMetalRoughTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),s=new jn({id:"defaultNormalsTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),i=new jn({id:"defaultEmissiveTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new jn({id:"defaultOcclusionTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=s,this._textures.defaultEmissiveTexture=i,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new kn({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:s,emissiveTexture:i,occlusionTexture:r})}get isPerformanceModel(){return!0}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),u.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Kl),u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),u.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),u.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),u.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),u.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0}_setLocalAABBDirty(){for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,s=new Uint8Array(t.length);for(let e=0,i=t.length;e{l.setImage(h,{minFilter:s,magFilter:i,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},h.src=e.src;break;default:this._textureTranscoder?E.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 jn({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 s,i,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(s=this._textures[e.colorTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(i=this._textures[e.metallicRoughnessTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else i=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 kn({id:t,model:this,colorTexture:s,metallicRoughnessTexture:i,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});this._textureSets[t]=a}createMesh(e){if(void 0===e.id||null===e.id)return void this.error("[createMesh] SceneModel.createMesh() config missing: id");if(this._scheduledMeshes[e.id])return void this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`);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 void this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`);if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),null;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),null;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'"),null;const t=!!this._dtxEnabled&&("triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive);if(e.origin=e.origin?u.addVec3(this._origin,e.origin,u.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||jl,s=e.position||Ql,i=e.rotation||Wl;u.eulerToQuaternion(i,"XYZ",zl),e.meshMatrix=u.composeMat4(s,zl,t,u.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Cr(e.positionsDecodeBoundary,u.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])]):Yl,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=u.vec3(),s=[];x(e.positions,s,t)&&(e.positions=s,e.origin=u.addVec3(e.origin,t,t))}if(e.positions){const t=u.collapseAABB3();e.positionsDecodeMatrix=u.mat4(),u.expandAABB3Points3(t,e.positions),e.positionsCompressed=br(e.positions,t,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=At(e.positions,e.indices,null,2):e.edgeIndices=At(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=Zl(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];x(e.positions,t,kl)&&(e.positions=t,e.origin=u.addVec3(e.origin,kl,u.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=At(e.positions,e.indices,null,2):e.edgeIndices=At(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return void this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`)}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return void this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)");if(e.geometry=this._geometries[e.geometryId],!e.geometry)return void this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`);if(e.origin=e.origin?u.addVec3(this._origin,e.origin,u.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.matrix)e.meshMatrix=e.matrix.slice();else{const t=e.scale||jl,s=e.position||Ql,i=e.rotation||Wl;u.eulerToQuaternion(i,"XYZ",zl),e.meshMatrix=u.composeMat4(s,zl,t,u.mat4())}if(!!this._dtxEnabled&&("triangles"===e.geometry.primitive||"solid"===e.geometry.primitive||"surface"===e.geometry.primitive)){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])]):Yl,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=Zl(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Yl,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId]),function(e){if(e.obb=u.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){const t=u.collapseAABB3();u.expandAABB3Points3(t,e.positionsCompressed),yt.decompressAABB(t,e.positionsDecodeMatrix),u.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){const t=u.collapseAABB3();u.expandAABB3Points3(t,e.positions),u.AABB3ToOBB3(t,e.obb)}}(e.geometry)}e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createMesh(e){const t=new ki(this,e.id,e.color,e.opacity);t.pickId=this.scene._renderer.getPickID(t);const s=t.pickId,i=s>>24&255,r=s>>16&255,o=s>>8&255,n=255&s;switch(e.pickColor=new Uint8Array([n,o,r,i]),e.worldAABB=u.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=u.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e);break;case 1:t.layer=this._getVBOBatchingLayer(e);break;case 0:t.layer=this._getVBOInstancingLayer(e)}t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.numPrimitives=e.numPrimitives,u.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t,this._meshList.push(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 s=0,i=e.buckets.length;s>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,s=e.origin,i=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${i}.${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":console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`),n=new Yo({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!1});break;case"solid":console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`),n=new Yo({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!0});break;case"lines":console.info(`[SceneModel ${this.id}]: creating LinesInstancingLayer`),n=new pn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0});break;case"points":console.info(`[SceneModel ${this.id}]: creating PointsInstancingLayer`),n=new Vn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=u.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=u.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=B),this._pickable&&!1!==e.pickable&&(t|=F),this._culled&&!1!==e.culled&&(t|=M),this._clippable&&!1!==e.clippable&&(t|=L),this._collidable&&!1!==e.collidable&&(t|=U),this._edges&&!1!==e.edges&&(t|=k),this._xrayed&&!1!==e.xrayed&&(t|=H),this._highlighted&&!1!==e.highlighted&&(t|=G),this._selected&&!1!==e.selected&&(t|=V),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];const s=u.collapseAABB3();for(let i=0,r=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,s=this.layerList.length;t0)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 s=0,i=t.visibleLayers.length;s65536?16:8)}else n=[{positionsCompressed:i,indices:r,edgeIndices:o}];return n}const ql=u.vec4(),Jl=u.vec4(),$l=u.vec3(),eh=u.vec3(),th=u.vec3(),sh=u.vec4(),ih=u.vec4(),rh=u.vec4();class oh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,s){let i=!1;const r=this._scene.camera;if(e){const t=u.subVec3(e,r.eye,$l);i=u.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=u.vec3();u.decomposeMat4(u.inverseMat4(this._scene.viewer.camera.viewMatrix,u.mat4()),t,u.vec4(),u.vec3());const s=u.distVec3(t,e);let i=Math.tan(Math.PI/500)*s*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(i/=this._scene.camera.ortho.scale/2),S(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new si(this._scene,ws({radius:i})),this._pivotSphere=new Os(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){u.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,u.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const s=t.boundary,i=s[2],r=s[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*i/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&&(S(this.getPivotPos(),this._rtcCenter,this._rtcPos),u.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 Dt(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=u.lookAtMat4v(e.eye,e.look,e.worldUp);u.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const s=this.getPivotPos();this._cameraOffset[2]+=u.distVec3(e.eye,s),t=u.inverseMat4(t);const i=u.transformVec3(t,this._cameraOffset),r=u.vec3();if(u.subVec3(e.eye,s,r),u.addVec3(r,i),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=u.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=u.normalizeVec3(u.subVec3(e.look,e.eye,nh)),s=u.cross3Vec3(t,e.worldUp,ah);return u.sqLenVec3(s)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,s=Math.abs(u.distVec3(this._scene.center,t.eye)),i=t.project.transposedMatrix,r=i.subarray(8,12),o=i.subarray(12),n=[0,0,-1,1],a=u.dotVec4(n,r)/u.dotVec4(n,o),l=hh;t.project.unproject(e,a,ch,Ah,l);const h=u.normalizeVec3(u.subVec3(l,t.eye,nh)),c=u.addVec3(t.eye,u.mulVec3Scalar(h,s,ah),lh);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const s=this._scene.camera;var i=-e;const r=-t;1===s.worldUp[2]&&(i=-i),this._azimuth+=.01*-i,this._polar+=.01*r,this._polar=u.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===s.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=u.lenVec3(u.subVec3(s.look,s.eye,u.vec3())),a=this.getPivotPos();u.addVec3(o,a);let l=u.lookAtMat4v(o,a,s.worldUp);l=u.inverseMat4(l);const h=u.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];s.eye=[l[12],l[13],l[14]],u.subVec3(s.eye,u.mulVec3Scalar(c,n),s.look),s.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 ph{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=u.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.snapPick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&e.snappedWorldPos?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents=!0):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,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._needFireEvents=!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=!0):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,cursorPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Ae;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.snappedWorldPos,e.cursorPos=this.pickCursorPos,e.canvasPos=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=!1}}destroy(){}}const dh=u.vec2();class fh{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController;let n,a,l,h=0,c=0,A=0,p=0,d=!1;const f=u.vec3();let m=!0;const E=this._scene.canvas.canvas,y=[];function g(e=!0){E.style.cursor="move",h=i.pointerCanvasPos[0],c=i.pointerCanvasPos[1],A=i.pointerCanvasPos[0],p=i.pointerCanvasPos[1],e&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(d=!0,f.set(o.pickResult.worldPos)):d=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!1}),E.addEventListener("mousedown",this._mouseDownHandler=t=>{if(s.active&&s.pointerEnabled)switch(t.which){case 1:y[e.input.KEY_SHIFT]||s.planView?(n=!0,g()):(n=!0,g(!1));break;case 2:a=!0,g();break;case 3:l=!0,s.panRightClick&&g()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!s.active||!s.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],A=t[3],p=i.pointerCanvasPos[0],m=i.pointerCanvasPos[1];if(y[e.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l){const t=p-h,s=m-c,i=e.camera;if("perspective"===i.projection){const o=Math.abs(d?u.lenVec3(u.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/A,r.panDeltaY+=1.5*s*o/A}else r.panDeltaX+=.5*i.ortho.scale*(t/A),r.panDeltaY+=.5*i.ortho.scale*(s/A)}else!n||a||l||s.planView||(s.firstPerson?(r.rotateDeltaY-=(p-h)/o*s.dragRotationRate/2,r.rotateDeltaX+=(m-c)/A*(s.dragRotationRate/4)):(r.rotateDeltaY-=(p-h)/o*(1.5*s.dragRotationRate),r.rotateDeltaX+=(m-c)/A*(1.5*s.dragRotationRate)));h=p,c=m}),E.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{s.active&&s.pointerEnabled&&i.mouseover&&(m=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),E.addEventListener("mouseup",this._mouseUpHandler=e=>{if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){let s=e.target,i=0,r=0,o=0,n=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,o+=s.scrollLeft,n+=s.scrollTop,s=s.offsetParent;t[0]=e.pageX+o-i,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,dh);const s=dh[0],i=dh[1];Math.abs(s-A)<3&&Math.abs(i-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:dh,event:e},!0)}E.style.removeProperty("cursor")}}),E.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.active&&s.pointerEnabled});const v=1/60;let I=null;E.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==I?t-I:0;I=t,o>.05&&(o=.05),o{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),h=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),A=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||h||c||A))return;const p=e.aabb,d=u.getAABB3Diag(p);u.getAABB3Center(p,mh);const f=Math.abs(d/Math.tan(t.cameraFlight.fitFOV*u.DEGTORAD)),m=1.1*d;Ih.orthoScale=m,n?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldRight,f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):a?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldForward,f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):l?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldRight,-f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):h?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldForward,-f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):c?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldUp,f,Eh),vh)),Ih.look.set(mh),Ih.up.set(u.normalizeVec3(u.mulVec3Scalar(o.worldForward,1,yh),gh))):A&&(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldUp,-f,Eh),vh)),Ih.look.set(mh),Ih.up.set(u.normalizeVec3(u.mulVec3Scalar(o.worldForward,-1,yh)))),!s.firstPerson&&s.followPointer&&t.pivotController.setPivotPos(mh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Ih,(()=>{t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Ih),t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Th{constructor(e,t,s,i,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,h=!1;const c=this._scene.canvas.canvas,A=s=>{let i;s&&s.worldPos&&(i=s.worldPos);const r=s&&s.entity?s.entity.aabb:e.aabb;if(i){const s=e.camera;u.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(l||h)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),A=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||A||u||p)if(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(h=!0);if(1===t.which&&s.active&&s.pointerEnabled&&(i.mouseDownClientX=t.clientX,i.mouseDownClientY=t.clientY,i.mouseDownCursorX=i.pointerCanvasPos[0],i.mouseDownCursorY=i.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(h=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!s.active||!s.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-i.mouseDownClientX)>3||Math.abs(r.clientY-i.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),h=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),p=a.hasSubs("doublePicked"),d=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||p||d||f))return(l||h||c)&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!s.firstPerson&&s.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0),this._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo||p||d,o.schedulePickSurface=o.schedulePickEntity&&d,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),s.doublePickFlyTo&&(A(o.pickResult),!s.firstPerson&&s.followPointer)){const e=o.pickResult.entity.aabb,s=u.getAABB3Center(e);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:i.pointerCanvasPos},!0),s.doublePickFlyTo&&(A(),!s.firstPerson&&s.followPointer)){const s=e.aabb,i=u.getAABB3Center(s);t.pivotController.setPivotPos(i),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 Rh{constructor(e,t,s,i,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=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&i.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(i=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&(n[i]=!1,i===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const h=t.cameraControl,c=a.deltaTime/1e3;if(!s.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,n),i=h._isKeyDownForAction(h.ROTATE_Y_NEG,n),o=h._isKeyDownForAction(h.ROTATE_X_POS,n),a=h._isKeyDownForAction(h.ROTATE_X_NEG,n),l=c*s.keyboardRotationRate;(e||i||o||a)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:i&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!s.firstPerson&&s.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,n),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,n);if(e||o){const n=c*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(i.followPointerDirty=!0,l=!1)}}const A=h._isKeyDownForAction(h.PAN_FORWARDS,n),u=h._isKeyDownForAction(h.PAN_BACKWARDS,n),p=h._isKeyDownForAction(h.PAN_LEFT,n),d=h._isKeyDownForAction(h.PAN_RIGHT,n),f=h._isKeyDownForAction(h.PAN_UP,n),m=h._isKeyDownForAction(h.PAN_DOWN,n),E=(n[o.KEY_ALT]?.3:1)*c*s.keyboardPanRate;(A||u||p||d||f||m)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=E:f&&(r.panDeltaY+=-E),d?r.panDeltaX+=-E:p&&(r.panDeltaX+=E),u?r.panDeltaZ+=E:A&&(r.panDeltaZ+=-E))}))}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 Ph=u.vec3();class Dh{constructor(e,t,s,i,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let h=1,c=1,A=null;this._onTick=e.on("tick",(()=>{if(!s.active||!s.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),s.followPointer&&--h<=0&&(h=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&s.followPointer&&i.followPointerDirty&&(n.pickCursorPos=i.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?A=n.pickResult.worldPos:(c=1,A=null),i.followPointerDirty=!1),A){const t=Math.abs(u.lenVec3(u.subVec3(A,e.camera.eye,Ph)));c=t/s.dollyProximityThreshold}c{i.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{i.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Ch(e,o,i.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{s.active&&s.pointerEnabled&&(Ch(e,o,i.pointerCanvasPos),i.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{s.active&&s.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 Ch(e,t,s){if(e){const{x:i,y:r}=t.getBoundingClientRect();s[0]=e.clientX-i,s[1]=e.clientY-r}else e=window.event,s[0]=e.x,s[1]=e.y;return s}const Nh=function(e,t){if(e){let s=e.target,i=0,r=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-i,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Oh{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=u.vec2(),l=u.vec2(),h=u.vec2(),c=u.vec2(),A=[],p=this._scene.canvas.canvas;let d=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),p.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!s.active||!s.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(i.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Nh(r[0],a),s.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),s.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!s.firstPerson&&n.startPivot()&&n.showPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),!s.firstPerson&&n.startPivot()&&n.showPivot()))));A.length{n.getPivoting()&&n.endPivot()}),p.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],p=n[3],m=t.touches;if(t.touches.length===d){if(1===d){Nh(m[0],l),u.subVec2(l,A[0],c);const t=c[0],o=c[1];if(null!==i.longTouchTimeout&&(Math.abs(t)>s.longTapRadius||Math.abs(o)>s.longTapRadius)&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),s.planView){const i=e.camera;if("perspective"===i.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/p*s.touchPanRate,r.panDeltaY+=o*n/p*s.touchPanRate}else r.panDeltaX+=.5*i.ortho.scale*(t/p)*s.touchPanRate,r.panDeltaY+=.5*i.ortho.scale*(o/p)*s.touchPanRate}else r.rotateDeltaY-=t/a*(1*s.dragRotationRate),r.rotateDeltaX+=o/p*(1.5*s.dragRotationRate)}else if(2===d){const t=m[0],n=m[1];Nh(t,l),Nh(n,h);const a=u.geometricMeanVec2(A[0],A[1]),c=u.geometricMeanVec2(l,h),d=u.vec2();u.subVec2(a,c,d);const f=d[0],E=d[1],y=e.camera,g=u.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),v=(u.distVec2(A[0],A[1])-g)*s.touchDollyRate;if(r.dollyDelta=v,Math.abs(v)<1)if("perspective"===y.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,i=Math.abs(u.lenVec3(u.subVec3(t,e.camera.eye,[])))*Math.tan(y.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*i/p*s.touchPanRate,r.panDeltaY-=E*i/p*s.touchPanRate}else r.panDeltaX-=.5*y.ortho.scale*(f/p)*s.touchPanRate,r.panDeltaY-=.5*y.ortho.scale*(E/p)*s.touchPanRate;i.pointerCanvasPos=c}for(let e=0;e{let i;s&&s.worldPos&&(i=s.worldPos);const r=s?s.entity.aabb:e.aabb;if(i){const s=e.camera;u.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};p.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!s.active||!s.pointerEnabled)return;null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,Sh(r[0],h);const o=h[0],n=h[1],l=r[0].pageX,A=r[0].pageY;i.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(A)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),i.longTouchTimeout=null}),s.longTapTimeout)}else c=-1;for(;l.length{if(!s.active||!s.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,p=n.hasSubs("pickedSurface");null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(A>-1&&c-A<325?(Sh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=p,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),s.doublePickFlyTo&&d(o.pickResult)):(n.fire("doublePickedNothing"),s.doublePickFlyTo&&d()),A=-1):u.distVec2(l[0],h)<4&&(Sh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=p,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),A=t),c=-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:u.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:u.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const s=this.scene;this._controllers={cameraControl:this,pickController:new ph(this,this._configs),pivotController:new uh(s,this._configs),panController:new oh(s),cameraFlight:new Ui(this,{duration:.5})},this._handlers=[new bh(this.scene,this._controllers,this._configs,this._states,this._updates),new Oh(this.scene,this._controllers,this._configs,this._states,this._updates),new fh(this.scene,this._controllers,this._configs,this._states,this._updates),new _h(this.scene,this._controllers,this._configs,this._states,this._updates),new Th(this.scene,this._controllers,this._configs,this._states,this._updates),new xh(this.scene,this._controllers,this._configs,this._states,this._updates),new Rh(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Dh(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",E.isString(e)){const t=this.scene.input,s={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":s[this.PAN_LEFT]=[t.KEY_A],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_Z],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":s[this.PAN_LEFT]=[t.KEY_Q],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_W],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=s}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const s=this._keyMap[e];if(!s)return!1;t||(t=this.scene.input.keyDown);for(let e=0,i=s.length;e0?Hh(t):null,n=s&&s.length>0?Hh(s):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&i.push(e.id);const s=e.children;if(s)for(var r=0,l=s.length;r>t;s.sort(ia);const i=new Int32Array(e.length);for(let t=0,r=s.length;te[t+1]){let s=e[t];e[t]=e[t+1],e[t+1]=s}ra=new Int32Array(e),t.sort(oa);const s=new Int32Array(e.length);for(let i=0,r=t.length;it){let s=e;e=t,t=s}function s(s,i){return s!==e?e-s:i!==t?t-i:0}let i=0,r=(o.length>>1)-1;for(;i<=r;){const e=r+i>>1,t=s(o[2*e],o[2*e+1]);if(t>0)i=e+1;else{if(!(t<0))return e;r=e-1}}return-i-1}const a=new Int32Array(o.length/2);a.fill(0);const l=i.length/3;if(l>8*(1<u.maxNumPositions&&(u=A()),u.bucketNumber>8)return[e];let d;-1===h[l]&&(h[l]=u.numPositions++,u.positionsCompressed.push(i[3*l]),u.positionsCompressed.push(i[3*l+1]),u.positionsCompressed.push(i[3*l+2])),-1===h[c]&&(h[c]=u.numPositions++,u.positionsCompressed.push(i[3*c]),u.positionsCompressed.push(i[3*c+1]),u.positionsCompressed.push(i[3*c+2])),-1===h[p]&&(h[p]=u.numPositions++,u.positionsCompressed.push(i[3*p]),u.positionsCompressed.push(i[3*p+1]),u.positionsCompressed.push(i[3*p+2])),u.indices.push(h[l]),u.indices.push(h[c]),u.indices.push(h[p]),(d=n(l,c))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(l,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(c,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]]))}const p=t/8*2,d=t/8,f=2*i.length+(r.length+o.length)*p;let m=0,E=-i.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*d,E+=e.positionsCompressed.length/3})),m>f?[e]:(s&&function(e,t){const s={};let i=0;e.forEach((e=>{const t=e.indices,r=e.edgeIndices,o=e.positionsCompressed;for(let e=0,i=t.length;e0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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,s=e._lightsState;if(this._program=new ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=s.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 sceneModelWorldMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),o.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),o.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform highp sampler2D uTextureModelMatrices;"),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=s.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, 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 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, 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*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),o.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),o.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),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=s.lights.length;e0,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"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const da=new Float32Array([1,1,1]),fa=u.vec3(),ma=u.vec3(),Ea=u.vec3(),ya=u.vec3(),ga=u.mat4();class va{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=fa;if(h){const t=ma;u.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,ga),m=Ea,m[0]=r.eye[0]-e[0],m[1]=r.eye[1]-e[1],m[2]=r.eye[2]-e[2]}else f=d,m=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),s===Wi.SILHOUETTE_XRAYED){const e=i.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.SILHOUETTE_HIGHLIGHTED){const e=i.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.SILHOUETTE_SELECTED){const e=i.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,da);if(i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const E=i._sectionPlanesState.sectionPlanes.length;if(E>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.y) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 Ia=new Float32Array([0,0,0,1]),_a=u.vec3(),Ta=u.vec3(),Ra=u.vec3(),Pa=u.mat4();class Da{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=_a;if(m){const t=u.transformPoint3(A,h,Ta);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,Pa)}else f=d;if(n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),s===Wi.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===Wi.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,Ia);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 ba=u.vec3(),Ca=u.vec3(),Na=u.vec3(),Oa=u.mat4();class Sa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=ba;if(m){const t=u.transformPoint3(A,h,Ca);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,Oa)}else f=d;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureEdgesColorRenderer"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled,s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push(" vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vec4 rgb = vec4(color.rgba);"),s.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 xa=u.vec3(),wa=u.vec3(),Ba=u.vec3(),Ma=u.mat4();class Fa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i;let d,f;l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=xa;if(m){const t=u.transformPoint3(A,h,wa);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=O(o.viewMatrix,e,Ma),f=Ba,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("smooth out vec4 vWorldPosition;"),s.push("flat out uvec4 vFlags2;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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=u.vec3(),Ua=u.vec3(),Ha=u.vec3(),Ga=u.vec3(),Va=u.mat4();class ka{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=e.pickViewMatrix||o.viewMatrix;let f,m;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const t=La;if(h){const e=Ua;u.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],f=O(d,t,Va),m=Ha,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),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._uWorldMatrix,!1,p),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 E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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 ja=u.vec3(),Qa=u.vec3(),Wa=u.vec3(),za=u.vec3(),Ka=u.vec3(),Ya=u.mat4();class Xa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=ja;let E,y;m[0]=u.safeInv(d[3]-d[0])*u.MAX_INT,m[1]=u.safeInv(d[4]-d[1])*u.MAX_INT,m[2]=u.safeInv(d[5]-d[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(m[0]),e.snapPickCoordinateScale[1]=u.safeInv(m[1]),e.snapPickCoordinateScale[2]=u.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=Qa;if(g){const e=u.transformPoint3(A,h,Wa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],E=O(f,t,Ya),y=za,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(_,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(_,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(_,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uSnapVectorA;"),s.push("uniform vec2 uSnapInvVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),s.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Za=u.vec3(),qa=u.vec3(),Ja=u.vec3(),$a=u.vec3(),el=u.vec3(),tl=u.mat4();class sl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=Za;let E,y;m[0]=u.safeInv(d[3]-d[0])*u.MAX_INT,m[1]=u.safeInv(d[4]-d[1])*u.MAX_INT,m[2]=u.safeInv(d[5]-d[2])*u.MAX_INT,e.snapPickCoordinateScale[0]=u.safeInv(m[0]),e.snapPickCoordinateScale[1]=u.safeInv(m[1]),e.snapPickCoordinateScale[2]=u.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=qa;if(g){const e=Ja;u.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],E=O(f,t,tl),y=$a,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uVectorAB;"),s.push("uniform vec2 uInverseVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),s.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" } else {"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const il=u.vec3(),rl=u.vec3(),ol=u.vec3(),nl=u.vec3(),al=u.mat4();class ll{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=i,d=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=il;if(h){const t=rl;u.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=O(d,e,al),m=ol,m[0]=o.eye[0]-e[0],m[1]=o.eye[1]-e[1],m[2]=o.eye[2]-e[2]}else f=d,m=o.eye;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" } else {"),s.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const hl=u.vec3(),cl=u.vec3(),Al=u.vec3(),ul=u.vec3(),pl=u.mat4();class dl{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=hl;if(m){const t=u.transformPoint3(A,h,cl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=O(r.viewMatrix,e,pl),f=Al,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),s&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 fl=u.vec3(),ml=u.vec3(),El=u.vec3(),yl=u.vec3(),gl=u.mat4();class vl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const m=0!==l[0]||0!==l[1]||0!==l[2],E=0!==h[0]||0!==h[1]||0!==h[2];if(m||E){const e=fl;if(m){const t=ml;u.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],d=O(p,e,gl),f=El,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=p,f=o.eye;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,A),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,i.worldNormalMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;t0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&he.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec3 normal;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 worldNormalMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 viewNormalMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),he.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(he.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&he.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&&he.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let e=0;e 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&&he.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 Il=u.vec3(),_l=u.vec3(),Tl=u.vec3(),Rl=u.vec3();u.vec4();const Pl=u.mat4();class Dl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:p}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=Il;if(m){const t=u.transformPoint3(A,h,_l);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=O(r.viewMatrix,e,Pl),f=Tl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,p),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ye(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("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;"),s&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),s&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;"),s){i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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(${u.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class bl{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._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=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 va(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Fa(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ka(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Dl(this._scene)),this._vertexDepthRenderer||(this._vertexDepthRenderer=new Xa(this._scene)),this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sl(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 va(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new dl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new vl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Da(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Sa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Fa(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Dl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Dl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ka(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new Xa(this._scene)),this._vertexDepthRenderer}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sl(this._scene)),this._snapDepthBufInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ll(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._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Cl={};class Nl{constructor(){this.positionsCompressed=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Ol{constructor(){this.texturePerObjectIdColorsAndFlags=null,this.texturePerObjectIdOffsets=null,this.texturePerObjectIdPositionsDecodeMatrix=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,s,i,r,o){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,s,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,i,3),this.texturePerObjectIdOffsets.bindTexture(e,o,4)}bindTriangleIndicesTextures(e,t,s,i){this.indicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.indicesPerBitnessTextures[i].bindTexture(e,s,6)}bindEdgeIndicesTextures(e,t,s,i){this.edgeIndicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[i].bindTexture(e,s,6)}}class Sl{constructor(e,t,s,i,r=null){this._gl=e,this._texture=t,this._textureWidth=s,this._textureHeight=i,this._textureData=r}bindTexture(e,t,s){return e.bindTexture(t,this,s)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const xl={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(xl,null,4));let e=0;Object.keys(xl).forEach((t=>{t.startsWith("size")&&(e+=xl[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/xl.totalPolygons).toFixed(2)}`);let t={};Object.keys(xl).forEach((s=>{s.startsWith("size")&&(t[s]=`${(xl[s]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class wl{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,s,i,r,o,n){const a=t.length;this.numPortions=a;const l=4096,h=Math.ceil(a/512);if(0===h)throw"texture height===0";const c=new Uint8Array(16384*h);xl.sizeDataColorsAndFlags+=c.byteLength,xl.numberOfTextures++;for(let e=0;e>24&255,i[e]>>16&255,i[e]>>8&255,255&i[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,h),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,h,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Sl(e,A,l,h,c)}generateTextureForObjectOffsets(e,t){const s=512,i=Math.ceil(t/s);if(0===i)throw"texture height===0";const r=new Float32Array(1536*i).fill(0);xl.sizeDataTextureOffsets+=r.byteLength,xl.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,s,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,i,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 Sl(e,o,s,i,r)}generateTextureForPositionsDecodeMatrices(e,t,s){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const r=2048,o=Math.ceil(i/512),n=new Float32Array(8192*o);xl.sizeDataPositionDecodeMatrices+=n.byteLength,xl.numberOfTextures++;const a=u.mat4();for(let e=0;e{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Cl[t],s._destroy()}))),s}(e.scene),this.model=e,this._buffer=new Nl,this._dataTextureState=new Ol,this._dataTextureGenerator=new wl,this._state=new He({origin:u.vec3(t.origin),metallicRoughnessBuf:null,positionsDecodeMatrix:u.mat4(),textureState:this._dataTextureState,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.aabb=u.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&xl.cannotCreatePortion.because10BitsObjectId++;let s=this._numPortions+t<=65536;const i=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[i]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let i=0,r=0;e.buckets.forEach((e=>{i+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+i>16777216||t+r>16777216)&&xl.cannotCreatePortion.becauseTextureSize++,s&&=this._state.numVertices+i<=16777216&&t+r<=16777216}return s}createPortion(e){if(this._finalized)throw"Already finalized";const t=[],s=e.worldAABB;e.buckets.forEach(((i,r)=>{const o=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#${r}`:`${e.id}#${r}`;let n=this._bucketGeometries[o];n||(n=this._createBucketGeometry(e,i),this._bucketGeometries[o]=n);const a=u.collapseAABB3(Ul),l=this._createSubPortion(e,n,i,a);u.expandAABB3(s,a),t.push(l)}));const i=this._state.origin;0===i[0]&&0===i[1]&&0===i[2]||(s[0]+=i[0],s[1]+=i[1],s[2]+=i[2],s[3]+=i[0],s[4]+=i[1],s[5]+=i[2]),u.expandAABB3(this.aabb,s);const r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(t),this.model.numPortions++,r}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;xl.overheadSizeAlignementIndices+=2*(e-t.indices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;xl.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.edgeIndices),t.edgeIndices=s}const s=t.positionsCompressed,i=t.indices,r=t.edgeIndices,o=this._buffer,n=o.positionsCompressed.length/3,a=s.length/3;for(let e=0,t=s.length;e0){let e,s=3*t.numTriangles;t.numVertices<=256?(e=h.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=s,xl.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=h.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=s,xl.totalPolygons16Bits+=t.numTriangles):(e=h.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=s,xl.totalPolygons32Bits+=t.numTriangles),xl.totalPolygons+=t.numTriangles;for(let s=0;s0){let e,s=2*t.numEdges;t.numVertices<=256?(e=h.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=s,xl.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=h.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=s,xl.totalEdges16Bits+=t.numEdges):(e=h.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=s,xl.totalEdges32Bits+=t.numEdges),xl.totalEdges+=t.numEdges;for(let s=0;s0&&(t.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId8Bits)),i.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId16Bits)),i.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId32Bits)),i.indices8Bits.length>0&&(t.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,i.indices8Bits)),i.indices16Bits.length>0&&(t.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,i.indices16Bits)),i.indices32Bits.length>0&&(t.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,i.indices32Bits)),i.edgeIndices8Bits.length>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(s,i.edgeIndices8Bits)),i.edgeIndices16Bits.length>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(s,i.edgeIndices16Bits)),i.edgeIndices32Bits.length>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(s,i.edgeIndices32Bits)),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,s){t&B&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&G&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&H&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&V&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&L&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&k&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&F&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&M&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&B?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&L?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(console.info("_uploadDeferredFlags"),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.texturePerObjectIdColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdColorsAndFlags._textureWidth,t.texturePerObjectIdColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectIdColorsAndFlags._textureData),e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdOffsets._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdOffsets._textureWidth,t.texturePerObjectIdOffsets._textureHeight,e.RGB,e.FLOAT,t.texturePerObjectIdOffsets._textureData)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdColorsAndFlags._texture),i.texSubImage2D(i.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,i.RGBA_INTEGER,i.UNSIGNED_BYTE,Fl)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,i=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),d.bindTexture(d.TEXTURE_2D,p.texturePerObjectIdColorsAndFlags._texture),d.texSubImage2D(d.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,d.RGBA_INTEGER,d.UNSIGNED_BYTE,Fl))}_setDeferredFlags(){}_setFlags2(e,t,s=!1){const i=this._portionToSubPortionsMap[e];for(let e=0,r=i.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectIdColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Fl))}_setDeferredFlags2(){}setOffset(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdOffsets._texture),i.texSubImage2D(i.TEXTURE_2D,0,0,e,1,1,i.RGB,i.FLOAT,Ll))}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._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,Wi.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,Wi.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._dataTextureRenderers.depthRenderer&&this._dataTextureRenderers.depthRenderer.drawLayer(t,this,Wi.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._dataTextureRenderers.normalsRenderer&&this._dataTextureRenderers.normalsRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,Wi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,Wi.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._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,Wi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,Wi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,Wi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,Wi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,Wi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.occlusionRenderer&&this._dataTextureRenderers.occlusionRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.shadowRenderer&&this._dataTextureRenderers.shadowRenderer.drawLayer(t,this,Wi.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,Wi.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,Wi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,Wi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,Wi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,Wi.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}}const kl=u.vec3();u.mat4();const jl=u.vec3([1,1,1]),Ql=u.vec3([0,0,0]),Wl=u.vec3([0,0,0]),zl=u.identityQuaternion(),Kl=u.identityMat4(),Yl=new Uint8Array([255,255,255]);class Xl extends C{constructor(e,t={}){super(e,t),this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!0,this._vboBatchingLayerScratchMemory=(Qi++,ji),this._textureTranscoder=t.textureTranscoder||function(e){const t=e.scene.id;let s=qn[t];return s||(s=new Zn({viewer:e}),qn[t]=s,e.scene.on("destroyed",(()=>{delete qn[t],s.destroy()}))),s}(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=u.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._entityList=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this._scheduledMeshes={},this.renderFlags=new gs,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._edgeThreshold=t.edgeThreshold||10,this._origin=u.vec3(t.origin||[0,0,0]),this._position=u.vec3(t.position||[0,0,0]),this._rotation=u.vec3(t.rotation||[0,0,0]),this._quaternion=u.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=u.vec4(t.quaternion||[0,0,0,1]),t.rotation&&u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=u.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=u.mat4(),this._worldRotationMatrixConjugate=u.mat4(),this._matrix=u.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=u.mat4(),u.inverseMat4(this._matrix,this._worldNormalMatrix),u.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=u.mat4(),this._viewNormalMatrix=u.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._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}_createDefaultTextureSet(){const e=new jn({id:"defaultColorTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new jn({id:"defaultMetalRoughTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),s=new jn({id:"defaultNormalsTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),i=new jn({id:"defaultEmissiveTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new jn({id:"defaultOcclusionTexture",texture:new Ks({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=s,this._textures.defaultEmissiveTexture=i,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new kn({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:s,emissiveTexture:i,occlusionTexture:r})}get isPerformanceModel(){return!0}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),u.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Kl),u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),u.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),u.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),u.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),u.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),u.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0}_setLocalAABBDirty(){for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,s=new Uint8Array(t.length);for(let e=0,i=t.length;e{l.setImage(h,{minFilter:s,magFilter:i,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},h.src=e.src;break;default:this._textureTranscoder?E.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 jn({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 s,i,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(s=this._textures[e.colorTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(i=this._textures[e.metallicRoughnessTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else i=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 kn({id:t,model:this,colorTexture:s,metallicRoughnessTexture:i,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});this._textureSets[t]=a}createMesh(e){if(void 0===e.id||null===e.id)return void this.error("[createMesh] SceneModel.createMesh() config missing: id");if(this._scheduledMeshes[e.id])return void this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`);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 void this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`);if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),null;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),null;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'"),null;const t=!!this._dtxEnabled&&("triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive);if(e.origin=e.origin?u.addVec3(this._origin,e.origin,u.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||jl,s=e.position||Ql,i=e.rotation||Wl;u.eulerToQuaternion(i,"XYZ",zl),e.meshMatrix=u.composeMat4(s,zl,t,u.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Cr(e.positionsDecodeBoundary,u.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])]):Yl,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=u.vec3(),s=[];x(e.positions,s,t)&&(e.positions=s,e.origin=u.addVec3(e.origin,t,t))}if(e.positions){const t=u.collapseAABB3();e.positionsDecodeMatrix=u.mat4(),u.expandAABB3Points3(t,e.positions),e.positionsCompressed=br(e.positions,t,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=At(e.positions,e.indices,null,2):e.edgeIndices=At(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=Zl(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];x(e.positions,t,kl)&&(e.positions=t,e.origin=u.addVec3(e.origin,kl,u.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=At(e.positions,e.indices,null,2):e.edgeIndices=At(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return void this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`)}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return void this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)");if(e.geometry=this._geometries[e.geometryId],!e.geometry)return void this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`);if(e.origin=e.origin?u.addVec3(this._origin,e.origin,u.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.matrix)e.meshMatrix=e.matrix.slice();else{const t=e.scale||jl,s=e.position||Ql,i=e.rotation||Wl;u.eulerToQuaternion(i,"XYZ",zl),e.meshMatrix=u.composeMat4(s,zl,t,u.mat4())}if(!!this._dtxEnabled&&("triangles"===e.geometry.primitive||"solid"===e.geometry.primitive||"surface"===e.geometry.primitive)){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])]):Yl,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=Zl(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Yl,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId]),function(e){if(e.obb=u.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){const t=u.collapseAABB3();u.expandAABB3Points3(t,e.positionsCompressed),yt.decompressAABB(t,e.positionsDecodeMatrix),u.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){const t=u.collapseAABB3();u.expandAABB3Points3(t,e.positions),u.AABB3ToOBB3(t,e.obb)}}(e.geometry)}e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createMesh(e){const t=new ki(this,e.id,e.color,e.opacity);t.pickId=this.scene._renderer.getPickID(t);const s=t.pickId,i=s>>24&255,r=s>>16&255,o=s>>8&255,n=255&s;switch(e.pickColor=new Uint8Array([n,o,r,i]),e.worldAABB=u.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=u.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e);break;case 1:t.layer=this._getVBOBatchingLayer(e);break;case 0:t.layer=this._getVBOInstancingLayer(e)}t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.numPrimitives=e.numPrimitives,u.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t,this._meshList.push(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 s=0,i=e.buckets.length;s>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,s=e.origin,i=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${i}.${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 Yo({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!1});break;case"solid":n=new Yo({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!0});break;case"lines":n=new pn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0});break;case"points":n=new Vn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=u.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=u.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=B),this._pickable&&!1!==e.pickable&&(t|=F),this._culled&&!1!==e.culled&&(t|=M),this._clippable&&!1!==e.clippable&&(t|=L),this._collidable&&!1!==e.collidable&&(t|=U),this._edges&&!1!==e.edges&&(t|=k),this._xrayed&&!1!==e.xrayed&&(t|=H),this._highlighted&&!1!==e.highlighted&&(t|=G),this._selected&&!1!==e.selected&&(t|=V),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];const s=u.collapseAABB3();for(let i=0,r=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,s=this.layerList.length;t0)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 s=0,i=t.visibleLayers.length;s65536?16:8)}else n=[{positionsCompressed:i,indices:r,edgeIndices:o}];return n}const ql=u.vec4(),Jl=u.vec4(),$l=u.vec3(),eh=u.vec3(),th=u.vec3(),sh=u.vec4(),ih=u.vec4(),rh=u.vec4();class oh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,s){let i=!1;const r=this._scene.camera;if(e){const t=u.subVec3(e,r.eye,$l);i=u.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=u.vec3();u.decomposeMat4(u.inverseMat4(this._scene.viewer.camera.viewMatrix,u.mat4()),t,u.vec4(),u.vec3());const s=u.distVec3(t,e);let i=Math.tan(Math.PI/500)*s*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(i/=this._scene.camera.ortho.scale/2),S(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new si(this._scene,ws({radius:i})),this._pivotSphere=new Os(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){u.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,u.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const s=t.boundary,i=s[2],r=s[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*i/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&&(S(this.getPivotPos(),this._rtcCenter,this._rtcPos),u.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 Dt(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=u.lookAtMat4v(e.eye,e.look,e.worldUp);u.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const s=this.getPivotPos();this._cameraOffset[2]+=u.distVec3(e.eye,s),t=u.inverseMat4(t);const i=u.transformVec3(t,this._cameraOffset),r=u.vec3();if(u.subVec3(e.eye,s,r),u.addVec3(r,i),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=u.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=u.normalizeVec3(u.subVec3(e.look,e.eye,nh)),s=u.cross3Vec3(t,e.worldUp,ah);return u.sqLenVec3(s)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,s=Math.abs(u.distVec3(this._scene.center,t.eye)),i=t.project.transposedMatrix,r=i.subarray(8,12),o=i.subarray(12),n=[0,0,-1,1],a=u.dotVec4(n,r)/u.dotVec4(n,o),l=hh;t.project.unproject(e,a,ch,Ah,l);const h=u.normalizeVec3(u.subVec3(l,t.eye,nh)),c=u.addVec3(t.eye,u.mulVec3Scalar(h,s,ah),lh);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const s=this._scene.camera;var i=-e;const r=-t;1===s.worldUp[2]&&(i=-i),this._azimuth+=.01*-i,this._polar+=.01*r,this._polar=u.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===s.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=u.lenVec3(u.subVec3(s.look,s.eye,u.vec3())),a=this.getPivotPos();u.addVec3(o,a);let l=u.lookAtMat4v(o,a,s.worldUp);l=u.inverseMat4(l);const h=u.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];s.eye=[l[12],l[13],l[14]],u.subVec3(s.eye,u.mulVec3Scalar(c,n),s.look),s.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 ph{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=u.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.snapPick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&e.snappedWorldPos?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents=!0):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,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._needFireEvents=!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=!0):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,cursorPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Ae;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.snappedWorldPos,e.cursorPos=this.pickCursorPos,e.canvasPos=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=!1}}destroy(){}}const dh=u.vec2();class fh{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController;let n,a,l,h=0,c=0,A=0,p=0,d=!1;const f=u.vec3();let m=!0;const E=this._scene.canvas.canvas,y=[];function g(e=!0){E.style.cursor="move",h=i.pointerCanvasPos[0],c=i.pointerCanvasPos[1],A=i.pointerCanvasPos[0],p=i.pointerCanvasPos[1],e&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(d=!0,f.set(o.pickResult.worldPos)):d=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!1}),E.addEventListener("mousedown",this._mouseDownHandler=t=>{if(s.active&&s.pointerEnabled)switch(t.which){case 1:y[e.input.KEY_SHIFT]||s.planView?(n=!0,g()):(n=!0,g(!1));break;case 2:a=!0,g();break;case 3:l=!0,s.panRightClick&&g()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!s.active||!s.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],A=t[3],p=i.pointerCanvasPos[0],m=i.pointerCanvasPos[1];if(y[e.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l){const t=p-h,s=m-c,i=e.camera;if("perspective"===i.projection){const o=Math.abs(d?u.lenVec3(u.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/A,r.panDeltaY+=1.5*s*o/A}else r.panDeltaX+=.5*i.ortho.scale*(t/A),r.panDeltaY+=.5*i.ortho.scale*(s/A)}else!n||a||l||s.planView||(s.firstPerson?(r.rotateDeltaY-=(p-h)/o*s.dragRotationRate/2,r.rotateDeltaX+=(m-c)/A*(s.dragRotationRate/4)):(r.rotateDeltaY-=(p-h)/o*(1.5*s.dragRotationRate),r.rotateDeltaX+=(m-c)/A*(1.5*s.dragRotationRate)));h=p,c=m}),E.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{s.active&&s.pointerEnabled&&i.mouseover&&(m=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),E.addEventListener("mouseup",this._mouseUpHandler=e=>{if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){let s=e.target,i=0,r=0,o=0,n=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,o+=s.scrollLeft,n+=s.scrollTop,s=s.offsetParent;t[0]=e.pageX+o-i,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,dh);const s=dh[0],i=dh[1];Math.abs(s-A)<3&&Math.abs(i-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:dh,event:e},!0)}E.style.removeProperty("cursor")}}),E.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.active&&s.pointerEnabled});const v=1/60;let I=null;E.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==I?t-I:0;I=t,o>.05&&(o=.05),o{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),h=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),A=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||h||c||A))return;const p=e.aabb,d=u.getAABB3Diag(p);u.getAABB3Center(p,mh);const f=Math.abs(d/Math.tan(t.cameraFlight.fitFOV*u.DEGTORAD)),m=1.1*d;Ih.orthoScale=m,n?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldRight,f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):a?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldForward,f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):l?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldRight,-f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):h?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldForward,-f,Eh),vh)),Ih.look.set(mh),Ih.up.set(o.worldUp)):c?(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldUp,f,Eh),vh)),Ih.look.set(mh),Ih.up.set(u.normalizeVec3(u.mulVec3Scalar(o.worldForward,1,yh),gh))):A&&(Ih.eye.set(u.addVec3(mh,u.mulVec3Scalar(o.worldUp,-f,Eh),vh)),Ih.look.set(mh),Ih.up.set(u.normalizeVec3(u.mulVec3Scalar(o.worldForward,-1,yh)))),!s.firstPerson&&s.followPointer&&t.pivotController.setPivotPos(mh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Ih,(()=>{t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Ih),t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Th{constructor(e,t,s,i,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,h=!1;const c=this._scene.canvas.canvas,A=s=>{let i;s&&s.worldPos&&(i=s.worldPos);const r=s&&s.entity?s.entity.aabb:e.aabb;if(i){const s=e.camera;u.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(l||h)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),A=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||A||u||p)if(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(h=!0);if(1===t.which&&s.active&&s.pointerEnabled&&(i.mouseDownClientX=t.clientX,i.mouseDownClientY=t.clientY,i.mouseDownCursorX=i.pointerCanvasPos[0],i.mouseDownCursorY=i.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(h=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!s.active||!s.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-i.mouseDownClientX)>3||Math.abs(r.clientY-i.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),h=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),p=a.hasSubs("doublePicked"),d=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||p||d||f))return(l||h||c)&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!s.firstPerson&&s.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0),this._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo||p||d,o.schedulePickSurface=o.schedulePickEntity&&d,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),s.doublePickFlyTo&&(A(o.pickResult),!s.firstPerson&&s.followPointer)){const e=o.pickResult.entity.aabb,s=u.getAABB3Center(e);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:i.pointerCanvasPos},!0),s.doublePickFlyTo&&(A(),!s.firstPerson&&s.followPointer)){const s=e.aabb,i=u.getAABB3Center(s);t.pivotController.setPivotPos(i),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 Rh{constructor(e,t,s,i,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=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&i.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(i=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&(n[i]=!1,i===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const h=t.cameraControl,c=a.deltaTime/1e3;if(!s.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,n),i=h._isKeyDownForAction(h.ROTATE_Y_NEG,n),o=h._isKeyDownForAction(h.ROTATE_X_POS,n),a=h._isKeyDownForAction(h.ROTATE_X_NEG,n),l=c*s.keyboardRotationRate;(e||i||o||a)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:i&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!s.firstPerson&&s.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,n),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,n);if(e||o){const n=c*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(i.followPointerDirty=!0,l=!1)}}const A=h._isKeyDownForAction(h.PAN_FORWARDS,n),u=h._isKeyDownForAction(h.PAN_BACKWARDS,n),p=h._isKeyDownForAction(h.PAN_LEFT,n),d=h._isKeyDownForAction(h.PAN_RIGHT,n),f=h._isKeyDownForAction(h.PAN_UP,n),m=h._isKeyDownForAction(h.PAN_DOWN,n),E=(n[o.KEY_ALT]?.3:1)*c*s.keyboardPanRate;(A||u||p||d||f||m)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=E:f&&(r.panDeltaY+=-E),d?r.panDeltaX+=-E:p&&(r.panDeltaX+=E),u?r.panDeltaZ+=E:A&&(r.panDeltaZ+=-E))}))}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 Ph=u.vec3();class Dh{constructor(e,t,s,i,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let h=1,c=1,A=null;this._onTick=e.on("tick",(()=>{if(!s.active||!s.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),s.followPointer&&--h<=0&&(h=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&s.followPointer&&i.followPointerDirty&&(n.pickCursorPos=i.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?A=n.pickResult.worldPos:(c=1,A=null),i.followPointerDirty=!1),A){const t=Math.abs(u.lenVec3(u.subVec3(A,e.camera.eye,Ph)));c=t/s.dollyProximityThreshold}c{i.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{i.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{Ch(e,o,i.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{s.active&&s.pointerEnabled&&(Ch(e,o,i.pointerCanvasPos),i.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{s.active&&s.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 Ch(e,t,s){if(e){const{x:i,y:r}=t.getBoundingClientRect();s[0]=e.clientX-i,s[1]=e.clientY-r}else e=window.event,s[0]=e.x,s[1]=e.y;return s}const Nh=function(e,t){if(e){let s=e.target,i=0,r=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-i,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Oh{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=u.vec2(),l=u.vec2(),h=u.vec2(),c=u.vec2(),A=[],p=this._scene.canvas.canvas;let d=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),p.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!s.active||!s.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(i.touchStartTime=Date.now(),1===r.length&&1===l.length&&(Nh(r[0],a),s.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),s.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!s.firstPerson&&n.startPivot()&&n.showPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),!s.firstPerson&&n.startPivot()&&n.showPivot()))));A.length{n.getPivoting()&&n.endPivot()}),p.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],p=n[3],m=t.touches;if(t.touches.length===d){if(1===d){Nh(m[0],l),u.subVec2(l,A[0],c);const t=c[0],o=c[1];if(null!==i.longTouchTimeout&&(Math.abs(t)>s.longTapRadius||Math.abs(o)>s.longTapRadius)&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),s.planView){const i=e.camera;if("perspective"===i.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/p*s.touchPanRate,r.panDeltaY+=o*n/p*s.touchPanRate}else r.panDeltaX+=.5*i.ortho.scale*(t/p)*s.touchPanRate,r.panDeltaY+=.5*i.ortho.scale*(o/p)*s.touchPanRate}else r.rotateDeltaY-=t/a*(1*s.dragRotationRate),r.rotateDeltaX+=o/p*(1.5*s.dragRotationRate)}else if(2===d){const t=m[0],n=m[1];Nh(t,l),Nh(n,h);const a=u.geometricMeanVec2(A[0],A[1]),c=u.geometricMeanVec2(l,h),d=u.vec2();u.subVec2(a,c,d);const f=d[0],E=d[1],y=e.camera,g=u.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),v=(u.distVec2(A[0],A[1])-g)*s.touchDollyRate;if(r.dollyDelta=v,Math.abs(v)<1)if("perspective"===y.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,i=Math.abs(u.lenVec3(u.subVec3(t,e.camera.eye,[])))*Math.tan(y.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*i/p*s.touchPanRate,r.panDeltaY-=E*i/p*s.touchPanRate}else r.panDeltaX-=.5*y.ortho.scale*(f/p)*s.touchPanRate,r.panDeltaY-=.5*y.ortho.scale*(E/p)*s.touchPanRate;i.pointerCanvasPos=c}for(let e=0;e{let i;s&&s.worldPos&&(i=s.worldPos);const r=s?s.entity.aabb:e.aabb;if(i){const s=e.camera;u.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};p.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!s.active||!s.pointerEnabled)return;null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,Sh(r[0],h);const o=h[0],n=h[1],l=r[0].pageX,A=r[0].pageY;i.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(A)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),i.longTouchTimeout=null}),s.longTapTimeout)}else c=-1;for(;l.length{if(!s.active||!s.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,p=n.hasSubs("pickedSurface");null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(A>-1&&c-A<325?(Sh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=p,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),s.doublePickFlyTo&&d(o.pickResult)):(n.fire("doublePickedNothing"),s.doublePickFlyTo&&d()),A=-1):u.distVec2(l[0],h)<4&&(Sh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=p,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),A=t),c=-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:u.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:u.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const s=this.scene;this._controllers={cameraControl:this,pickController:new ph(this,this._configs),pivotController:new uh(s,this._configs),panController:new oh(s),cameraFlight:new Ui(this,{duration:.5})},this._handlers=[new bh(this.scene,this._controllers,this._configs,this._states,this._updates),new Oh(this.scene,this._controllers,this._configs,this._states,this._updates),new fh(this.scene,this._controllers,this._configs,this._states,this._updates),new _h(this.scene,this._controllers,this._configs,this._states,this._updates),new Th(this.scene,this._controllers,this._configs,this._states,this._updates),new xh(this.scene,this._controllers,this._configs,this._states,this._updates),new Rh(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new Dh(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",E.isString(e)){const t=this.scene.input,s={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":s[this.PAN_LEFT]=[t.KEY_A],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_Z],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":s[this.PAN_LEFT]=[t.KEY_Q],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_W],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=s}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const s=this._keyMap[e];if(!s)return!1;t||(t=this.scene.input.keyDown);for(let e=0,i=s.length;e0?Hh(t):null,n=s&&s.length>0?Hh(s):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&i.push(e.id);const s=e.children;if(s)for(var r=0,l=s.length;r * Copyright (c) 2022 Niklas von Hertzen diff --git a/dist/xeokit-bim-viewer.min.umd.js b/dist/xeokit-bim-viewer.min.umd.js index 3488f954..5fa826b1 100644 --- a/dist/xeokit-bim-viewer.min.umd.js +++ b/dist/xeokit-bim-viewer.min.umd.js @@ -1,4 +1,4 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).bundle={})}(this,(function(e){"use strict";class t{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 s=new t;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class r{constructor(){this.items=[]}}class o{constructor(e,t,s,i,r){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=i,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class n{constructor(e={}){this._id=s.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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const s=this._getNextId(),n=new i(s);for(let s=0,i=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new o(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(r);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);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,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}class a{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}let l=!0,h=l?Float64Array:Float32Array;const c=new h(16),A=new h(16),u=new h(4),p={setDoublePrecisionEnabled(e){l=e,h=l?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>l,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new h(e||2),vec3:e=>new h(e||3),vec4:e=>new h(e||4),mat3:e=>new h(e||9),mat3ToMat4:(e,t=new h(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 h(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const i=new h(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,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new h(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>p.dotVec4(e,e),lenVec4:e=>Math.sqrt(p.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=>p.dotVec3(e,e),sqLenVec2:e=>p.dotVec2(e,e),lenVec3:e=>Math.sqrt(p.sqLenVec3(e)),distVec3:(()=>{const e=new h(3);return(t,s)=>p.lenVec3(p.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(p.sqLenVec2(e)),distVec2:(()=>{const e=new h(2);return(t,s)=>p.lenVec2(p.subVec2(t,s,e))})(),rcpVec3:(e,t)=>p.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/p.lenVec4(e);return p.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/p.lenVec3(e);return p.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/p.lenVec2(e);return p.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=p.dotVec3(e,t)/Math.sqrt(p.sqLenVec3(e)*p.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new h(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=p.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=p.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=p.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||p.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:()=>p.m4s(0),setMat4ToOnes:()=>p.m4s(1),diagonalMat4v:e=>new h([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,i)=>p.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>p.diagonalMat4c(e,e,e,e),identityMat4:(e=new h(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 h(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>p.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],E=e[14],y=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],D=t[7],b=t[8],C=t[9],N=t[10],O=t[11],S=t[12],x=t[13],w=t[14],B=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*E,s[3]=g*n+v*c+I*d+_*y,s[4]=T*i+R*a+P*A+D*f,s[5]=T*r+R*l+P*u+D*m,s[6]=T*o+R*h+P*p+D*E,s[7]=T*n+R*c+P*d+D*y,s[8]=b*i+C*a+N*A+O*f,s[9]=b*r+C*l+N*u+O*m,s[10]=b*o+C*h+N*p+O*E,s[11]=b*n+C*c+N*d+O*y,s[12]=S*i+x*a+w*A+B*f,s[13]=S*r+x*l+w*u+B*m,s[14]=S*o+x*h+w*p+B*E,s[15]=S*n+x*c+w*d+B*y,s},mulMat3(e,t,s){s||(s=new h(9));const i=e[0],r=e[3],o=e[6],n=e[1],a=e[4],l=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],E=t[4],y=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*E+o*v,s[6]=i*f+r*y+o*I,s[1]=n*p+a*m+l*g,s[4]=n*d+a*E+l*v,s[7]=n*f+a*y+l*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*E+u*v,s[8]=c*f+A*y+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=p.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],E=e[15],y=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,D=c*E-p*d,b=A*m-u*f,C=A*E-p*f,N=u*E-p*m,O=1/(y*N-g*C+v*b+I*D-_*P+T*R);return t[0]=(a*N-l*C+h*b)*O,t[1]=(-i*N+r*C-o*b)*O,t[2]=(f*T-m*_+E*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*N+l*D-h*P)*O,t[5]=(s*N-r*D+o*P)*O,t[6]=(-d*T+m*v-E*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*C-a*D+h*R)*O,t[9]=(-s*C+i*D-o*R)*O,t[10]=(d*_-f*v+E*y)*O,t[11]=(-c*_+A*v-p*y)*O,t[12]=(-n*b+a*P-l*R)*O,t[13]=(s*b-i*P+r*R)*O,t[14]=(-d*I+f*g-m*y)*O,t[15]=(c*I-A*g+u*y)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||p.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||p.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new h(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.translationMat4v(e,r))})(),translationMat4s:(e,t)=>p.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>p.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=p.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,u,d,f,m;return c=a*l,A=l*h,u=h*a,d=a*r,f=l*r,m=h*r,(s=s||p.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*u-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*u+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>p.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=p.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=p.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new h(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>p.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=p.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,u=i*h,d=r*l,f=r*h,m=o*h,E=n*a,y=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=u-y,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+E,s[7]=0,s[8]=u+y,s[9]=f-E,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=p.vec4()){const i=p.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],u=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,u),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,u),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,u),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,u),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,u))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,u),s[1]=0)),s},composeMat4:(e,t,s,i=p.mat4())=>(p.quaternionToRotationMat4(t,i),p.scaleMat4v(s,i),p.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new h(3),t=new h(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=p.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=p.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=p.lenVec3(e);p.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,p.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=p.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],u=t[2];if(r===c&&o===A&&n===u)return p.identityMat4();let d,f,m,E,y,g,v,I,_,T;return d=r-c,f=o-A,m=n-u,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,E=l*m-h*f,y=h*d-a*m,g=a*f-l*d,T=Math.sqrt(E*E+y*y+g*g),T?(T=1/T,E*=T,y*=T,g*=T):(E=0,y=0,g=0),v=f*g-m*y,I=m*E-d*g,_=d*y-f*E,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=E,i[1]=v,i[2]=d,i[3]=0,i[4]=y,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(E*r+y*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>p.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=p.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];p.addVec4(r,i,c),p.subVec4(r,i,A);const o=2*i[2],n=A[0],a=A[1],l=A[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=c[0]/n,s[9]=c[1]/a,s[10]=-c[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],p.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,s=p.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=p.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],E=e[8],y=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new h(16),t=new h(16),s=new h(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||p.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||p.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=p.vec4()){const i=e[0]*p.DEGTORAD/2,r=e[1]*p.DEGTORAD/2,o=e[2]*p.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=p.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const u=s+n+c;return u>0?(A=.5/Math.sqrt(u+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=p.vec4()){const i=Math.sqrt(p.dotVec3(e,e)*p.dotVec3(t,t));let r=i+p.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):p.cross3Vec3(e,t,s),s[3]=r,p.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=p.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new h(16);return(t,s,i)=>(i=i||p.vec3(),p.quaternionToRotationMat4(t,e),p.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=p.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=p.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,u=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-u*-a,s[1]=A*h+d*-a+u*-n-c*-l,s[2]=u*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=p.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,u=n*s,d=a*s,f=l*s,m=a*i,E=l*i,y=l*r;return t[0]=1-(m+y),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(u+y),t[6]=E+h,t[8]=f+c,t[9]=E-h,t[10]=1-(u+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,E=o*l;return t[0]=1-(u+d),t[4]=c-E,t[8]=A+m,t[1]=c+E,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=p.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>p.normalizeQuaternion(p.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=p.vec4()){const s=(e=p.normalizeQuaternion(e,u))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,t},AABB3:e=>new h(e||6),AABB2:e=>new h(e||4),OBB3:e=>new h(e||32),OBB2:e=>new h(e||16),Sphere3:(e,t,s,i)=>new h([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],E=e[9],y=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new h(3),t=new h(3),s=new h(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],p.subVec3(t,e,s),Math.abs(p.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new h(3),t=new h(3),s=new h(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=p.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(p.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||p.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||p.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=p.AABB3())=>(e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MAX_DOUBLE,e[3]=p.MIN_DOUBLE,e[4]=p.MIN_DOUBLE,e[5]=p.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=p.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 h(3);return(t,s,i)=>{s=s||p.AABB3();let r,o,n,a=p.MAX_DOUBLE,l=p.MAX_DOUBLE,h=p.MAX_DOUBLE,c=p.MIN_DOUBLE,A=p.MIN_DOUBLE,u=p.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>u&&(u=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=u,s}})(),OBB3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new h(3);return(t,s)=>{s=s||p.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new h(3),t=new h(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new h(3),t=new h(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=p.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=p.vec3()){let s=0,i=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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MIN_DOUBLE,e[3]=p.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=p.AABB2()){let s,i,r,o,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+3*e*e*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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=p.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,u=r*l-o*a,d=Math.sqrt(c*c+A*A+u*u);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=u/d),i},rayTriangleIntersect:(()=>{const e=new h(3),t=new h(3),s=new h(3),i=new h(3),r=new h(3);return(o,n,a,l,h,c)=>{c=c||p.vec3();const A=p.subVec3(l,a,e),u=p.subVec3(h,a,t),d=p.cross3Vec3(n,u,s),f=p.dotVec3(A,d);if(f<1e-6)return null;const m=p.subVec3(o,a,i),E=p.dotVec3(m,d);if(E<0||E>f)return null;const y=p.cross3Vec3(m,A,r),g=p.dotVec3(n,y);if(g<0||E+g>f)return null;const v=p.dotVec3(u,y)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new h(3),t=new h(3),s=new h(3),i=new h(3);return(r,o,n,a,l,h)=>{h=h||p.vec3(),o=p.normalizeVec3(o,e);const c=p.subVec3(a,n,t),A=p.subVec3(l,n,s),u=p.cross3Vec3(c,A,i);p.normalizeVec3(u,u);const d=-p.dotVec3(n,u),f=-(p.dotVec3(r,u)+d)/p.dotVec3(o,u);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new h(3),t=new h(3),s=new h(3);return(i,r,o,n,a)=>{const l=p.subVec3(n,r,e),h=p.subVec3(o,r,t),c=p.subVec3(i,r,s),A=p.dotVec3(l,l),u=p.dotVec3(l,h),d=p.dotVec3(l,c),f=p.dotVec3(h,h),m=p.dotVec3(h,c),E=A*f-u*u;if(0===E)return null;const y=1/E,g=(f*d-u*m)*y,v=(A*m-u*d)*y;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=p.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,E=0;for(f=0,m=e.length;f{const e=new h(3),t=new h(3),s=new h(3),i=new h(3),r=new h(3),o=new h(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let u,d,f,m,E,y,g;for(h=0,c=a.length;h{const e=new h(3),t=new h(3),s=new h(3),i=new h(3),r=new h(3),o=new h(3),n=new h(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const u=1e4;let d,f,m,E,y,g;for(f=0,E=e.length;f{const e=new h(4),t=new h(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,p.transformVec4(s,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],p.transformVec3(s,e,t),p.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new h(16),t=new h(16),s=new h(4),i=new h(4),r=new h(4),o=new h(4);return(n,a,l,h,c,A)=>{const u=p.mulMat4(l,a,e),d=p.inverseMat4(u,t),f=n.width,m=n.height,E=(h[0]-f/2)/(f/2),y=-(h[1]-m/2)/(m/2);s[0]=E,s[1]=y,s[2]=-1,s[3]=1,p.transformVec4(d,s,i),p.mulVec4Scalar(i,1/i[3]),r[0]=E,r[1]=y,r[2]=1,r[3]=1,p.transformVec4(d,r,o),p.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],p.subVec3(o,i,A),p.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new h(3),t=new h(3);return(s,i,r,o,n,a,l)=>{p.canvasPosToWorldRay(s,i,r,n,e,t),p.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new h(16),t=new h(4),s=new h(4);return(i,r,o,n,a)=>{const l=p.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,p.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],p.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new h(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let l,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,l=0,c=s.length;ln[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(s.length<20||o>10)return a.triangles=s,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 p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let E=0;for(l=0,c=s.length;l{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};p.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),i=s+e[1],r=s;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),s=new Uint8Array(e);for(var n=0;n=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}},_={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let R,P=0,D=0;const b=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(b.scenes[e.id])return void console.error(`[ERROR] Scene ${y.inQuotes(e.id)} already exists`)}else e.id=v.addItem({});b.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;g[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{v.removeItem(e.id),delete b.scenes[e.id],delete g[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in b.scenes)b.scenes.hasOwnProperty(t)&&(e=b.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete b.scenes[e.id]))},this.scheduleTask=function(e,t){I.push(e),I.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;I.length>0&&(e<0||i0&&R>0){var t=1e3/R;D+=t,T.push(t),T.length>=30&&(D-=T.shift()),d.frame.fps=Math.round(D/T.length)}!function(e){const t=b.runTasks(e+10),s=b.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in _.time=e,b.scenes)if(b.scenes.hasOwnProperty(t)){var s=b.scenes[t];_.sceneId=t,_.startTime=s.startTime,_.deltaTime=null!=_.prevTime?_.time-_.prevTime:0,s.fire("tick",_,!0)}_.prevTime=e}(e),function(){const e=b.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=g[n],i||(i=g[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),P=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C);class N{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 N))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+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 s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(y.isNumeric(s)||y.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+y.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+y.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+y.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():b.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(p.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Y.set(this._viewPos),Y[3]=1,p.transformPoint4(this.scene.camera.projMatrix,Y,X);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+X[0]/X[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-X[1]/X[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 K?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]),x(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 q{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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.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,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class J{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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),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.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 s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ${constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+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 ee=p.vec3(),te=p.vec3();class se extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new Z(s,t.origin),this._cornerMarker=new Z(s,t.corner),this._targetMarker=new Z(s,t.target),this._originWorld=p.vec3(),this._cornerWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new q(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new q(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new $(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,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=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){const u=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>u||f>u||m>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);p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const E=this._container.getBoundingClientRect();for(var r=i.top-E.top,o=i.left-E.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{switch(e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red"),r=!0,o=e.entity,l.set(e.worldPos),h.set(e.canvasPos),this._mouseState){case 0:this.markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this.markerDiv.style.marginTop=e.canvasPos[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(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,i&&(i.visible=!0,i.centerPos=e.cursorPos,i.cursorPos=e.cursorPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class oe extends a{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 re(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,s=e.corner,i=e.target,r=new se(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.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]})),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,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const ae=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class le extends N{constructor(e,t={}){super(e,t),this._backgroundColor=p.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new ne(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-"+p.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?ce.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?ce.FS_MAX_FLOAT_PRECISION="mediump":ce.FS_MAX_FLOAT_PRECISION="lowp":ce.FS_MAX_FLOAT_PRECISION="mediump",ce.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),ce.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),ce.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),ce.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),ce.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ce.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),ce.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),ce.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),ce.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),ce.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){ce.SUPPORTED_EXTENSIONS[e]=!0})))}class ue{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class pe{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function ye(e){console.error(e.join("\n"))}class ge{constructor(e,t){this.id=me.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 pe(e,e.VERTEX_SHADER,Ee(this.source.vertex)),this._fragmentShader=new pe(e,e.FRAGMENT_SHADER,Ee(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ye(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ye(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ye(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ye(this.errors);let t,s,i,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 ye(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.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 Ie{constructor(e,t){this.scene=e,this.aabb=p.AABB3(),this.origin=p.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){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new Ie(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ie(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new ge(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),u=Math.random(),d="perspective"===i.camera.projection;Pe[0]=o,Pe[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,Pe),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ge(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const i=new Float32Array([1,1,0,1,0,0,1,0]),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 ve(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new ve(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new ve(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const be=new Float32Array(we(17,[0,1])),Ce=new Float32Array(we(17,[1,0])),Ne=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(xe(i,t));return s}(17,4)),Oe=new Float32Array(2);class Se{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 ge(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new ve(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new ve(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ve(e,e.ELEMENT_ARRAY_BUFFER,i,i.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Oe[0]=n,Oe[1]=a,i.uniform2fv(this._uViewport,Oe),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Ce):i.uniform2fv(this._uSampleOffsets,be),i.uniform1fv(this._uSampleWeights,Ne);const A=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function xe(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function we(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class Be{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(e=null){if(this._touch(e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(e=null){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=i.createTexture();let o;i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e?i.texStorage2D(i.TEXTURE_2D,1,e,t,s):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,s,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,a),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r,depthTexture:o,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,i=null,r=Uint8Array,o=4){const n=e,a=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,l=new r(o),h=this.gl;return h.readPixels(n,a,1,1,s||h.RGBA,i||h.UNSIGNED_BYTE,l,0),l}readArray(e=null,t=null,s=Uint8Array,i=4){const r=new s(this.buffer.width*this.buffer.height*i),o=this.gl;return o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,r,0),r}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.lastProgramId=null,e.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.lastProgramId=null,e.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=l.size[0],i=t%s-Math.floor(s/2),o=Math.floor(t/s)-Math.floor(s/2),a=Math.sqrt(Math.pow(i,2)+Math.pow(o,2));y.push({x:i,y:o,dist:a,isVertex:r&&n?d[e+3]>p.length/2:r,result:[d[e+0],d[e+1],d[e+2],d[e+3]]})}let g=null,v=null;if(y.length>0){y.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),v=y[0].isVertex?"vertex":"edge",y=y[0].result;const e=p[y[3]],t=e.origin,s=e.coordinateScale;g=[y[0]*s[0]+t[0],y[1]*s[1]+t[1],y[2]*s[2]+t[2]]}if(null===f&&null==g)return null;let _=null;return null!==g&&(_=e.camera.projectWorldPos(g)),{snapType:v,snappedToVertex:"vertex"===v,snappedToEdge:"edge"===v,worldPos:f,snappedWorldPos:g,snappedCanvasPos:_}},this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new Re(e,I),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){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.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 h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=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()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=(e,t)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",s,!0)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!0)}))}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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 He=new t({});class Ge{constructor(e){this.id=He.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){He.removeItem(this.id)}}class Ve extends N{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Ge({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],s=e[3];this._state.boundary=[0,0,t,s],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class ke extends N{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),p.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class je extends N{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),p.orthoMat4c(n,a,h,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Qe extends N{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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(){p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class We extends N{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const ze=p.vec3(),Ke=p.vec3(),Ye=p.vec3(),Xe=p.vec3(),Ze=p.vec3(),qe=p.vec3(),Je=p.vec4(),$e=p.vec4(),et=p.vec4(),tt=p.mat4(),st=p.mat4(),it=p.vec3(),rt=p.vec3(),ot=p.vec3(),nt=p.vec3();class at extends N{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Ge({deviceMatrix:p.mat4(),hasDeviceMatrix:!1,matrix:p.mat4(),normalMatrix:p.mat4(),inverseMatrix:p.mat4()}),this._perspective=new ke(this),this._ortho=new je(this),this._frustum=new Qe(this),this._customProjection=new We(this),this._project=this._perspective,this._eye=p.vec3([0,0,10]),this._look=p.vec3([0,0,0]),this._up=p.vec3([0,1,0]),this._worldUp=p.vec3([0,1,0]),this._worldRight=p.vec3([1,0,0]),this._worldForward=p.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?(p.subVec3(this._eye,this._look,it),p.normalizeVec3(it,rt),p.mulVec3Scalar(rt,1e3,ot),p.addVec3(this._look,ot,nt),t=nt):t=this._eye,e.hasDeviceMatrix?(p.lookAtMat4v(t,this._look,this._up,st),p.mulMat4(e.deviceMatrix,st,e.matrix)):p.lookAtMat4v(t,this._look,this._up,e.matrix),p.inverseMat4(this._state.matrix,this._state.inverseMatrix),p.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=p.subVec3(this._eye,this._look,ze);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tt),t=p.transformPoint3(tt,t,Ke),this.eye=p.addVec3(this._look,t,Ye),this.up=p.transformPoint3(tt,this._up,Xe)}orbitPitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._eye,this._look,ze);const s=p.cross3Vec3(p.normalizeVec3(t,Ke),p.normalizeVec3(this._up,Ye));p.rotationMat4v(.0174532925*e,s,tt),t=p.transformPoint3(tt,t,Xe),this.up=p.transformPoint3(tt,this._up,Ze),this.eye=p.addVec3(t,this._look,qe)}yaw(e){let t=p.subVec3(this._look,this._eye,ze);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tt),t=p.transformPoint3(tt,t,Ke),this.look=p.addVec3(t,this._eye,Ye),this._gimbalLock&&(this.up=p.transformPoint3(tt,this._up,Xe))}pitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._look,this._eye,ze);const s=p.cross3Vec3(p.normalizeVec3(t,Ke),p.normalizeVec3(this._up,Ye));p.rotationMat4v(.0174532925*e,s,tt),this.up=p.transformPoint3(tt,this._up,qe),t=p.transformPoint3(tt,t,Xe),this.look=p.addVec3(t,this._eye,Ze)}pan(e){const t=p.subVec3(this._eye,this._look,ze),s=[0,0,0];let i;if(0!==e[0]){const r=p.cross3Vec3(p.normalizeVec3(t,[]),p.normalizeVec3(this._up,Ke));i=p.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=p.mulVec3Scalar(p.normalizeVec3(this._up,Ye),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=p.mulVec3Scalar(p.normalizeVec3(t,Xe),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=p.addVec3(this._eye,s,Ze),this.look=p.addVec3(this._look,s,qe)}zoom(e){const t=p.subVec3(this._eye,this._look,ze),s=Math.abs(p.lenVec3(t,Ke)),i=Math.abs(s+e);if(i<.5)return;const r=p.normalizeVec3(t,Ye);this.eye=p.addVec3(this._look,p.mulVec3Scalar(r,i),Xe)}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=p.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 p.lenVec3(p.subVec3(this._look,this._eye,ze))}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=Je,s=$e,i=et;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,p.mulMat4v4(this.viewMatrix,t,s),p.mulMat4v4(this.projMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class lt extends N{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class ht extends lt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Ge({type:"dir",dir:p.vec3([1,1,1]),color:p.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=p.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];p.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=p.identityMat4()),p.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Be(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 ct extends lt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:p.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 At extends N{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var ut=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();const pt=function(){const e=p.mat4(),t=p.mat4();return function(s,i){i=i||p.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return p.identityMat4(e),p.translationMat4v(s,e),p.identityMat4(t),p.scalingMat4v([a/c,l/c,h/c],t),p.mulMat4(e,t,i),i}}();var dt=function(){const e=p.mat4(),t=p.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[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[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function Et(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function yt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const gt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=mt(e,a,"floor","ceil"),i=Et(s),o=yt(e,a,i),o>n&&(r=s,n=o),s=mt(e,a,"ceil","ceil"),i=Et(s),o=yt(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},vt=d.memory,It=p.AABB3();class _t extends At{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ge({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=gt.getPositionsBounds(t.positions),i=gt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=gt.getUVBounds(t.uv),i=gt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=gt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),vt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),vt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ve(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),vt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new ve(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),vt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ve(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),vt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ve(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),vt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=ut(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),vt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=p.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new ve(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),vt.positions+=this._pickTrianglePositionsBuf.numItems,vt.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),gt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=gt.getPositionsBounds(e),i=gt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),gt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),gt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=p.AABB3()),p.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=p.OBB3()),p.positions3ToAABB3(this._state.positions,It,this._state.positionsDecodeMatrix),p.AABB3ToOBB3(It,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(),vt.meshes--}}function Tt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return y.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Rt extends N{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const Pt={opaque:0,mask:1,blend:2},Dt=["opaque","mask","blend"];class bt extends Rt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Ge({type:"PhongMaterial",ambient:p.vec3([1,1,1]),diffuse:p.vec3([1,1,1]),specular:p.vec3([1,1,1]),emissive:p.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=Pt[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 Dt[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 Ct={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Nt extends Rt{get type(){return"EmphasisMaterial"}get presets(){return Ct}constructor(e,t={}){super(e,t),this._state=new Ge({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=Ct[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(Ct).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Ot={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 St extends Rt{get type(){return"EdgeMaterial"}get presets(){return Ot}constructor(e,t={}){super(e,t),this._state=new Ge({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=Ot[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(Ot).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const xt={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 wt extends N{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=p.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return xt}set units(e){e||(e="meters");xt[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=p.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=p.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 Bt extends N{constructor(e,t={}){super(e,t),this._supported=ce.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 Mt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Ft extends Rt{get type(){return"PointsMaterial"}get presets(){return Mt}constructor(e,t={}){super(e,t),this._state=new Ge({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=Mt[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(Mt).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 Lt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Ut extends Rt{get type(){return"LinesMaterial"}get presets(){return Lt}constructor(e,t={}){super(e,t),this._state=new Ge({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=Lt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Lt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ht(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Le(this,{transparent:i,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,i=t.length;e0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=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=p.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],y.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&b.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=Ht(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=Ht(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t{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=p.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.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);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.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=s.sectionPlanes.length;e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),A=ps(e),u=i.sectionPlanes.length>0,p=us(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),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(A){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("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&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(p){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=ps(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=us(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));p&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+As[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("}")),(A||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 = "+As[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+As[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+As[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+As[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+As[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){h&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),A&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||A)&&(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 s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class ys{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.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);"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.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;"));i&&(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=s.sectionPlanes.length;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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const gs=new t({}),vs=p.vec3(),Is=function(e,t){this.id=gs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ys(t),this._allocate(t)},_s={};Is.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=_s[t];return s||(s=new Is(t,e),_s[t]=s,d.memory.programs++),s._useCount++,s},Is.prototype.put=function(){0==--this._useCount&&(gs.removeItem(this.id),this._program&&this._program.destroy(),delete _s[this._hash],d.memory.programs--)},Is.prototype.webglContextRestored=function(){this._program=null},Is.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._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),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.sectionPlanes.length>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;"));i&&(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=s.sectionPlanes.length;e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Rs=new t({}),Ps=p.vec3(),Ds=function(e,t){this.id=Rs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ts(t),this._allocate(t)},bs={};Ds.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=bs[t];return s||(s=new Ds(t,e),bs[t]=s,d.memory.programs++),s._useCount++,s},Ds.prototype.put=function(){0==--this._useCount&&(Rs.removeItem(this.id),this._program&&this._program.destroy(),delete bs[this._hash],d.memory.programs--)},Ds.prototype.webglContextRestored=function(){this._program=null},Ds.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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;"),i){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 Ns=p.vec3(),Os=function(e,t){this._hash=e,this._shaderSource=new Cs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ss={};Os.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Ss[t];if(!s){if(s=new Os(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ss[t]=s,d.memory.programs++}return s._useCount++,s},Os.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ss[this._hash],d.memory.programs--)},Os.prototype.webglContextRestored=function(){this._program=null},Os.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},Os.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ge(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 ws=p.vec3(),Bs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new xs(t),this._allocate(t)},Ms={};Bs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ms[t];if(!s){if(s=new Bs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ms[t]=s,d.memory.programs++}return s._useCount++,s},Bs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ms[this._hash],d.memory.programs--)},Bs.prototype.webglContextRestored=function(){this._program=null},Bs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 Ls=p.vec3(),Us=function(e,t){this._hash=e,this._shaderSource=new Fs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Hs={};Us.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Hs[t];if(!s){if(s=new Us(t,e),s.errors)return console.log(s.errors.join("\n")),null;Hs[t]=s,d.memory.programs++}return s._useCount++,s},Us.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Hs[this._hash],d.memory.programs--)},Us.prototype.webglContextRestored=function(){this._program=null},Us.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.sectionPlanes.length>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),i){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 Vs=function(e,t){this._hash=e,this._shaderSource=new Gs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ks={};Vs.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=ks[s];if(!i){if(i=new Vs(s,e),i.errors)return console.log(i.errors.join("\n")),null;ks[s]=i,d.memory.programs++}return i._useCount++,i},Vs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ks[this._hash],d.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Vs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ge(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ti=function(){const e=p.vec3(),t=p.vec3(),s=p.vec3(),i=p.vec3(),r=p.vec3(),o=p.vec3(),n=p.vec4(),a=p.vec3(),l=p.vec3(),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3(),E=p.vec4(),y=p.vec4(),g=p.vec4(),v=p.vec3(),I=p.vec3(),_=p.vec3(),T=p.vec3(),R=p.vec3(),P=p.vec3(),D=p.vec3(),b=p.vec3(),C=p.vec3(),N=p.vec3(),O=p.vec3();return function(x,w,B,M){var F=M.primIndex;if(null!=F&&F>-1){const G=x.geometry._state,V=x.scene,k=V.camera,j=V.canvas;if("triangles"===G.primitiveName){M.primitive="triangle";const V=F,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var L=Q[V+0],U=Q[V+1],H=Q[V+2];o[0]=L,o[1]=U,o[2]=H,M.indices=o,z=3*L,K=3*U,Y=3*H}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(gt.decompressPosition(s,e,s),gt.decompressPosition(i,e,i),gt.decompressPosition(r,e,r))}M.canvasPos?p.canvasPosToLocalRay(j.canvas,x.origin?S(w,x.origin):w,B,x.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&p.worldRayToLocalRay(x.worldMatrix,M.origin,M.direction,e,t),p.normalizeVec3(t),p.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,E[0]=n[0],E[1]=n[1],E[2]=n[2],E[3]=1,p.transformVec4(x.worldMatrix,E,y),a[0]=y[0],a[1]=y[1],a[2]=y[2],M.canvasPos&&x.origin&&(a[0]+=x.origin[0],a[1]+=x.origin[1],a[2]+=x.origin[2]),M.worldPos=a,p.transformVec4(k.matrix,y,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,p.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=G.normals;if(X){if(G.compressGeometry){const e=3*L,t=3*U,s=3*H;gt.decompressNormal(X.subarray(e,e+2),c),gt.decompressNormal(X.subarray(t,t+2),A),gt.decompressNormal(X.subarray(s,s+2),u)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],u[0]=X[Y],u[1]=X[Y+1],u[2]=X[Y+2];const e=p.addVec3(p.addVec3(p.mulVec3Scalar(c,h[0],v),p.mulVec3Scalar(A,h[1],I),_),p.mulVec3Scalar(u,h[2],T),R);M.worldNormal=p.normalizeVec3(p.transformVec3(x.worldNormalMatrix,e,P))}const Z=G.uv;if(Z){if(d[0]=Z[2*L],d[1]=Z[2*L+1],f[0]=Z[2*U],f[1]=Z[2*U+1],m[0]=Z[2*H],m[1]=Z[2*H+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(gt.decompressUV(d,e,d),gt.decompressUV(f,e,f),gt.decompressUV(m,e,m))}M.uv=p.addVec3(p.addVec3(p.mulVec2Scalar(d,h[0],D),p.mulVec2Scalar(f,h[1],b),C),p.mulVec2Scalar(m,h[2],N),O)}}}}}();function si(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],E=[],g=[],v=[];let I,_,T,R,P,D,b,C,N,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,D=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),E.push(P*T),E.push(x),E.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(D+h),m.push(P*R+c);for(I=0;I0){for(N=m.length/3,E.push(0),E.push(1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(t*T),E.push(1),E.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(N=m.length/3,E.push(0),E.push(-1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(s*T),E.push(-1),E.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=fi(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=fi(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=fi(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,gi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,gi(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,fi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,fi(s,this.magFilter)));const a=fi(s,this.format,this.encoding),l=fi(s,this.type),h=yi(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class Ti extends N{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ge({texture:new Ei({gl:this.scene.canvas.gl}),matrix:p.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=p.vec2([0,0]),this._scale=p.vec2([1,1]),this._rotate=p.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return(e=e||Zt)!==Kt&&e!==Yt&&e!==Zt&&e!==zt&&e!==Wt&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=Zt),e}_checkMagFilter(e){return(e=e||Kt)!==Kt&&e!==Qt&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=Kt),e}_checkWrapS(e){return(e=e||Vt)!==kt&&e!==jt&&e!==Vt&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Vt),e}_checkWrapT(e){return(e=e||Vt)!==kt&&e!==jt&&e!==Vt&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Vt),e}_checkFlipY(e){return!!e}_checkEncoding(e){return(e=e||ls)!==ls&&e!==hs&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=ls),e}_webglContextRestored(){this._state.texture=new Ei({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=p.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=p.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?p.mulMat4(t,s):s),0!==this._rotate&&(s=p.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?p.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=vi(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=vi(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}const Ri=d.memory,Pi=p.AABB3();class Di extends At{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ge({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=p.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=gt.getPositionsBounds(t.positions),o=gt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new ve(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),Ri.positions+=s.positionsBuf.numItems,p.positions3ToAABB3(t.positions,this._aabb),p.positions3ToAABB3(r,Pi,s.positionsDecodeMatrix),p.AABB3ToOBB3(Pi,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new ve(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),Ri.colors+=s.colorsBuf.numItems}if(t.uv){const e=gt.getUVBounds(t.uv),r=gt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new ve(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),Ri.uvs+=s.uvBuf.numItems}if(t.normals){const e=gt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new ve(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),Ri.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),Ri.indices+=s.indicesBuf.numItems;const o=ut(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Ri.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(),Ri.meshes--}}var bi={};function Ci(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,E=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,D,b,C=0,N=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],u=[],d=[];let f,m,E,g,v,I,_,T,R,P,D,b;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),E=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(E+a),c.push(g+l),c.push(v+h),u.push(1-_/i),u.push(T/r),I=p.normalizeVec3(p.subVec3([E,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,D=(i+1)*(T-1)+_,b=(i+1)*T+_,d.push(R),d.push(P),d.push(D),d.push(D),d.push(b),d.push(R);return y.apply(e,{positions:c,normals:A,uv:u,indices:d})}bi.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},bi.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(bi.parse._buffToStr(e));window.location.href=s},bi.clone=function(e){return JSON.parse(JSON.stringify(e))},bi.bin={},bi.bin.f=new Float32Array(1),bi.bin.fb=new Uint8Array(bi.bin.f.buffer),bi.bin.rf=function(e,t){for(var s=bi.bin.f,i=bi.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},bi.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},bi.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},bi.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},bi.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},bi.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},bi.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},bi.parse={},bi.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class Oi extends N{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=p.vec3(t.pos||[0,0,0]),this._up=p.vec3(t.up||[0,1,0]),this._normal=p.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=p.vec3(),this._rtcPos=p.vec3(),this._imageSize=p.vec2(),this._texture=new Ti(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 di(this,{matrix:p.inverseMat4(p.lookAtMat4v(this._pos,p.subVec3(this._pos,this._normal,p.mat4()),this._up,p.mat4())),children:[this._bitmapMesh=new ei(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new _t(this,Ci({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new bt(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 Si=p.vec3(),xi=p.vec3(),wi=p.mat4();class Bi{constructor(){this.normal=p.vec3(),this.offset=0,this.testVertex=p.vec3()}set(e,t,s,i){const r=1/Math.sqrt(e*e+t*t+s*s);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=s*r,this.offset=i*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class Mi{constructor(){this.planes=[new Bi,new Bi,new Bi,new Bi,new Bi,new Bi]}}function Fi(e,t){let s=Mi.INSIDE;const i=Si,r=xi;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return Mi.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=Mi.INTERSECT)}return s}Mi.INSIDE=0,Mi.INTERSECT=1,Mi.OUTSIDE=2;class Li extends N{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=p.vec3(),r=w(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,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}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),y=Object.entries(E).map((([e,t])=>({color:e,components:t})));o.components.coloring=y;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=Qi(e.location,Ui),s=Qi(e.direction,Ui);h&&p.negateVec3(s),p.subVec3(t,l),r.yUp&&(t=zi(t),s=zi(s)),new ri(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];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),s.push(r++),s.push(r++))})),new Li(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=Qi(e.location,Hi),n=Qi(e.normal,Gi),a=Qi(e.up,Vi),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=zi(o),n=zi(n),a=zi(a)),new Oi(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.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&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!1),r.space_boundaries_visible)}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const 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((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=Qi(e.perspective_camera.camera_view_point,Ui),h=Qi(e.perspective_camera.camera_direction,Ui),c=Qi(e.perspective_camera.camera_up_vector,Ui),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=Qi(e.orthogonal_camera.camera_view_point,Ui),h=Qi(e.orthogonal_camera.camera_direction,Ui),c=Qi(e.orthogonal_camera.camera_up_vector,Ui),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),p.subVec3(a,l),r.yUp&&(a=zi(a),h=zi(h),c=zi(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:p.addVec3(a,h,Ui)}else h=p.addVec3(a,h,Ui);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.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 s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=p.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function ji(e){return{x:e[0],y:e[1],z:e[2]}}function Qi(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Wi(e){return new Float64Array([e[0],-e[2],e[1]])}function zi(e){return new Float64Array([e[0],e[2],-e[1]])}const Ki=p.vec3(),Yi=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class Xi extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new Z(s,t.origin),this._targetMarker=new Z(s,t.target),this._originWorld=p.vec3(),this._targetWorld=p.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 i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new q(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new q(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new q(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new q(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new $(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new $(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new $(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new $(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;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&&(p.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);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=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,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,E=s.unitsInfo[m].abbrev;for(var u=0,d=i.length;u{r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this._markerDiv.style.marginTop=e.canvasPos[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red")):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.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.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null)}destroy(){this.deactivate(),super.destroy()}}class Ji extends a{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._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 qi(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,s=e.target,i=new Xi(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.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,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}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,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(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,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=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),i=!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 er{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const i=tr(e,s);return i?t?sr(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=tr(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=sr(r,[t]),s&&(r=sr(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(e,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new t),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=e;const o=this._events[e];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function tr(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?lr._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(p.subVec3(i.eye,i.look,ar),i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,or),i.look=p.subVec3(or,ar,rr)):this._flyingLook&&(i.look=p.lerpVec3(s,0,1,this._look1,this._look2,rr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,nr)):this._flyingEyeLookUp&&(i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,or),i.look=p.lerpVec3(s,0,1,this._look1,this._look2,rr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,nr)),this._projection2){const t="ortho"===this._projection2?lr._easeOutExpo(e,0,1,1):lr._easeInCubic(e,0,1,1);i.customProjection.matrix=p.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();b.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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 hr extends N{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new lr(this),this._t=0,this.state=hr.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case hr.SCRUBBING:return;case hr.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=hr.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case hr.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=hr.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=hr.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=hr.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=hr.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=hr.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=hr.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=hr.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}hr.STOPPED=0,hr.SCRUBBING=1,hr.PLAYING=2,hr.PLAYING_TO=3,p.vec3(),p.vec3(),p.vec3(),p.vec3([0,-1,0]),p.vec4([0,0,0,1]);const cr=p.vec3();class Ar{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,s){this.numObjects=0,this._mask=s?y.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const n=t._sectionPlanesState.sectionPlanes,a=r*o,l=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;yr[0]=s,yr[1]=i,yr[2]=t.blendCutoff,yr[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,yr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===fr[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===fr[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===fr[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?Er:mr)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class Tr extends _r{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class Rr extends Tr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Pr extends _r{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class Dr extends Pr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class br extends _r{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class Cr extends _r{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class Nr extends _r{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class Or extends _r{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class Sr extends Tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class xr extends Tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.sectionPlanes.length>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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 Br extends Rr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class Mr extends Rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class Fr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class Lr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Ur extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Hr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Gr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class Vr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class kr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class jr extends Tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Wr extends Tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.sectionPlanes.length>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=i.sectionPlanes.length;e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;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=s.lights.length;e5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Xr=p.mat4(),Zr=p.mat4();function qr(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,u=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function eo(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const to=p.vec3(),so=p.vec3(),io=p.vec3(),ro=p.vec3(),oo=p.mat4();class no extends _r{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=to;let m,E;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=so;if(l){const e=io;p.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=S(d,t,oo),E=ro,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ao=p.vec3(),lo=p.vec3(),ho=p.vec3(),co=p.vec3(),Ao=p.mat4();class uo extends _r{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ao;let m,E;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=lo;if(l){const e=ho;p.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=S(d,t,Ao),E=co,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class po{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new no(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new uo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new no(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new uo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const fo={};const mo=p.mat4(),Eo=p.mat4(),yo=p.vec4([0,0,0,1]),go=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.OBB3();const vo=p.vec3(),Io=p.vec3(),_o=p.vec3(),To=p.vec3(),Ro=p.vec3(),Po=p.vec3(),Do=p.vec3();class bo{constructor(e){console.info("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Kr[t];return s||(s=new zr(e),Kr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Kr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=fo[t];return s||(s=new po(e),fo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete fo[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Yr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ge({origin:p.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=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=p.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=p.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=p.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)for(let e=0,t=r.length;e0){const e=mo;m?p.inverseMat4(p.transposeMat4(m,Eo),e):p.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,u=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=$r(d,"floor","ceil"),a=eo(n),h=o(d,a),h>c&&(l=n,c=h),n=$r(d,"ceil","ceil"),a=eo(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,i,i.length,v.normals,v.normals.length)}if(a)for(let e=0,t=a.length;e0)for(let e=0,t=o.length;e0)for(let e=0,t=n.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):qr(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=p.mat4());if(e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new ve(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new ve(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=gt.getUVBounds(s.uv),r=gt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=p.mat3(r.decodeMatrix),e.uvBuf=new ve(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new ve(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ve(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,i,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;ey)&&(y=e,i.set(g),r&&p.triangleNormal(d,f,m,r),E=!0)}}return E&&r&&(p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),E}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 Co extends Pr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class No extends Pr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,r;const o=t.sectionPlanes.length>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,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class So extends Dr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class xo extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class wo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class Bo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Mo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Fo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Lo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 Uo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Ho extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const Go={3e3:"linearToLinear",3001:"sRGBToLinear"};class Vo extends Pr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),i.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 = "+Go[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Go[i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class jo extends Pr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.sectionPlanes.length>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=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Jo=p.vec3(),$o=p.vec3(),en=p.vec3(),tn=p.vec3(),sn=p.mat4();class rn extends _r{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Jo;let m,E;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=$o;if(l){const e=p.transformPoint3(c,l,en);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=S(d,t,sn),E=tn,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class on{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new qo(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new rn(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new qo(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new rn(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const nn={};const an=new Uint8Array(4),ln=new Float32Array(1),hn=p.vec4([0,0,0,1]),cn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]);const An=new Float32Array(3),un=p.vec3(),pn=p.vec3(),dn=p.vec3(),fn=p.vec3(),mn=p.vec3(),En=p.vec3(),yn=p.vec3();class gn{constructor(e){console.info("Creating TrianglesInstancingLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Wo[t];return s||(s=new Qo(e),Wo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Wo[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=nn[t];return s||(s=new on(e),nn[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete nn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ge({numInstances:0,obb:p.OBB3(),origin:p.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf: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._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=p.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,i=e.roughness,r=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,o=e.meshMatrix,n=e.aabb,a=e.pickColor;if(this._finalized)throw"Already finalized";const l=t[0],h=t[1],c=t[2];if(this._colors.push(l),this._colors.push(h),this._colors.push(c),this._colors.push(r),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=i?i:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(o[0]),this._modelMatrixCol0.push(o[4]),this._modelMatrixCol0.push(o[8]),this._modelMatrixCol0.push(o[12]),this._modelMatrixCol1.push(o[1]),this._modelMatrixCol1.push(o[5]),this._modelMatrixCol1.push(o[9]),this._modelMatrixCol1.push(o[13]),this._modelMatrixCol2.push(o[2]),this._modelMatrixCol2.push(o[6]),this._modelMatrixCol2.push(o[10]),this._modelMatrixCol2.push(o[14]),this._state.geometry.normals){let e=p.transposeMat4(o,p.mat4()),t=p.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]);const A=this._state.geometry.positionsCompressed.length,u=this._state.geometry.positionsCompressed,d=this._state.geometry.positionsDecodeMatrix;for(let e=0;e0){let t=!1;e.colorsBuf=new ve(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new ve(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new ve(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new ve(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=p.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new ve(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new ve(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new ve(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";an[0]=t[0],an[1]=t[1],an[2]=t[2],an[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(an,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&M),r=!!(t&G),o=!!(t&V),n=!!(t&k),a=!!(t&j),l=!!(t&L),h=!!(t&F);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?fr.NOT_RENDERED:s?fr.COLOR_TRANSPARENT:fr.COLOR_OPAQUE,A=!i||h?fr.NOT_RENDERED:n?fr.SILHOUETTE_SELECTED:o?fr.SILHOUETTE_HIGHLIGHTED:r?fr.SILHOUETTE_XRAYED:fr.NOT_RENDERED;let u=0;u=!i||h?fr.NOT_RENDERED:n?fr.EDGES_SELECTED:o?fr.EDGES_HIGHLIGHTED:r?fr.EDGES_XRAYED:a?s?fr.EDGES_COLOR_TRANSPARENT:fr.EDGES_COLOR_OPAQUE:fr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?fr.PICK:fr.NOT_RENDERED)<<12,p|=(t&U?1:0)<<16,ln[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(ln,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(An[0]=t[0],An[1]=t[1],An[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(An,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=hn,u=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&p.triangleNormal(f,m,E,r),y=!0)}}return y&&r&&(p.transformVec3(a.normalMatrix,r,r),p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),y}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 vn extends Nr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class In extends Nr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class _n{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new vn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new In(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Tn={};class Rn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const Pn=p.vec4([0,0,0,1]),Dn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.OBB3();class bn{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Tn[t];return s||(s=new _n(e),Tn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Tn[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new Rn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ge({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=qr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ve(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 Or{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class On{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Cn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Nn(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Sn={};const xn=new Uint8Array(4),wn=new Float32Array(1),Bn=p.vec4([0,0,0,1]),Mn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]);const Fn=new Float32Array(3);class Ln{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=Sn[t];return s||(s=new On(e),Sn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Sn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ge({obb:p.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=p.vec3(e.origin)),this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,i=e.meshMatrix,r=e.aabb;if(this._finalized)throw"Already finalized";const o=t[0],n=t[1],a=t[2];t[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),p.collapseAABB3(r);const l=this._state.obb,h=l.length;for(let e=0;e0){let t=!1;this._state.colorsBuf=new ve(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";xn[0]=t[0],xn[1]=t[1],xn[2]=t[2],xn[3]=t[3],this._state.colorsBuf.setData(xn,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&M),r=!!(t&G),o=!!(t&V),n=!!(t&k),a=!!(t&j),l=!!(t&L),h=!!(t&F);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?fr.NOT_RENDERED:s?fr.COLOR_TRANSPARENT:fr.COLOR_OPAQUE,A=!i||h?fr.NOT_RENDERED:n?fr.SILHOUETTE_SELECTED:o?fr.SILHOUETTE_HIGHLIGHTED:r?fr.SILHOUETTE_XRAYED:fr.NOT_RENDERED;let u=0;u=!i||h?fr.NOT_RENDERED:n?fr.EDGES_SELECTED:o?fr.EDGES_HIGHLIGHTED:r?fr.EDGES_XRAYED:a?s?fr.EDGES_COLOR_TRANSPARENT:fr.EDGES_COLOR_OPAQUE:fr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?fr.PICK:fr.NOT_RENDERED)<<12,p|=(t&U?255:0)<<16,wn[0]=p,this._state.flagsBuf.setData(wn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Fn[0]=t[0],Fn[1]=t[1],Fn[2]=t[2],this._state.offsetsBuf.setData(Fn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Un extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Hn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 Gn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class Vn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class kn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class jn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Un(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Hn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Gn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new kn(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Qn={};class Wn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const zn=p.vec4(),Kn=p.vec4(),Yn=p.vec4([0,0,0,1]),Xn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.OBB3();class Zn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=Qn[t];return s||(s=new jn(e),Qn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Qn[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Wn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ge({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,i=e.color,r=e.colorsCompressed,o=e.colors,n=e.meshMatrix,a=e.worldAABB,l=e.pickColor,h=this._buffer,c=h.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=qr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ve(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Jn extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class $n extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class ea extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class ta extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class sa extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 ia extends Cr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class ra{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new qn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new sa(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new $n(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ea(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ta(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ia(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const oa={};const na=new Uint8Array(4),aa=new Float32Array(1),la=p.vec4([0,0,0,1]),ha=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]);const ca=new Float32Array(3);class Aa{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=oa[t];return s||(s=new ra(e),oa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete oa[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ge({obb:p.OBB3(),numInstances:0,origin:e.origin?p.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),p.collapseAABB3(s);const r=this._state.obb,o=r.length;for(let e=0;e0){let i=!1;s.flagsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new ve(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=p.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new ve(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;s.pickColorsBuf=new ve(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";na[0]=t[0],na[1]=t[1],na[2]=t[2],this._state.colorsBuf.setData(na,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&M),r=!!(t&G),o=!!(t&V),n=!!(t&k),a=!!(t&j),l=!!(t&L),h=!!(t&F);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?fr.NOT_RENDERED:s?fr.COLOR_TRANSPARENT:fr.COLOR_OPAQUE,A=!i||h?fr.NOT_RENDERED:n?fr.SILHOUETTE_SELECTED:o?fr.SILHOUETTE_HIGHLIGHTED:r?fr.SILHOUETTE_XRAYED:fr.NOT_RENDERED;let u=0;u=!i||h?fr.NOT_RENDERED:n?fr.EDGES_SELECTED:o?fr.EDGES_HIGHLIGHTED:r?fr.EDGES_XRAYED:a?s?fr.EDGES_COLOR_TRANSPARENT:fr.EDGES_COLOR_OPAQUE:fr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?fr.PICK:fr.NOT_RENDERED)<<12,p|=(t&U?255:0)<<16,aa[0]=p,this._state.flagsBuf.setData(aa,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ca[0]=t[0],ca[1]=t[1],ca[2]=t[2],this._state.offsetsBuf.setData(ca,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,fr.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,fr.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,fr.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class ua{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 pa{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const da={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={}}};const fa=new class{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==ma[e])return void ma[e].push({onLoad:t,onProgress:s,onError:i});ma[e]=[],ma[e].push({onLoad:t,onProgress:s,onError:i});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 s=ma[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{da.add(e,t);const s=ma[e];delete ma[e];for(let e=0,i=s.length;e{const s=ma[e];if(void 0===s)throw this.manager.itemError(e),t;delete ma[e];for(let e=0,i=s.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 ya{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 i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let ga=0;class va{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new ya,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Ea;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new Ea;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=va.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(va.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(va.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(va.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),ga>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),ga++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?Kt:Xt,magFilter:1===o.length?Kt:Xt,encoding:2===A?hs:ls,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),ga--}}va.BasisFormat={ETC1S:0,UASTC_4x4:1},va.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},va.EngineFormat={RGBAFormat:qt,RGBA_ASTC_4x4_Format:ns,RGBA_BPTC_Format:as,RGBA_ETC2_EAC_Format:os,RGBA_PVRTC_4BPPV1_Format:is,RGBA_S3TC_DXT5_Format:ts,RGB_ETC1_Format:36196,RGB_ETC2_Format:rs,RGB_PVRTC_4BPPV1_Format:ss,RGB_S3TC_DXT1_Format:Jt},va.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),E=n.getDFDFlags(),{transcoderFormat:y,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i{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 s=this._eventSubs[e];s||(s=[],this._eventSubs[e]=s),s.push(t)}fire(e,t){const s=this._eventSubs[e];if(s)for(let e=0,i=s.length;e{const s=this._getNextId(),n=new i(s);for(let s=0,i=e.length;s0,h=this._getNextId(),c=s.getTitle||(()=>s.title||""),A=s.doAction||s.callback||(()=>{}),u=s.getEnabled||(()=>!0),p=s.getShown||(()=>!0),d=new o(h,c,A,u,p);if(d.parentMenu=n,a.items.push(d),l){const e=t(r);d.subMenu=e,e.parentItem=d}this._itemList.push(d),this._itemMap[d.id]=d}}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 s=t.groups;for(let t=0,i=s.length;t'),s.push("
    "),t)for(let e=0,i=t.length;e'+l+" [MORE]"):s.push('
  • '+l+"
  • ")}}s.push("
"),s.push("");const i=s.join("");document.body.insertAdjacentHTML("beforeend",i);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,s=t.length;e{e.preventDefault();const s=t.subMenu;if(!s)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==s.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const i=t.itemElement,r=s.menuElement,a=i.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(s.id,a.left-200,a.top-1):o._showMenu(s.id,a.right-5,a.top-1),n=s})),i||(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&&(s=window.innerHeight-i),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=s+"px"}_hideMenuElement(e){e.style.display="none"}}class a{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}let l=!0,h=l?Float64Array:Float32Array;const c=new h(16),A=new h(16),u=new h(4),p={setDoublePrecisionEnabled(e){l=e,h=l?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>l,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new h(e||2),vec3:e=>new h(e||3),vec4:e=>new h(e||4),mat3:e=>new h(e||9),mat3ToMat4:(e,t=new h(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 h(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const i=new h(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,s=4294967295*Math.random()|0,i=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&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&i|128]}${e[i>>8&255]}-${e[i>>16&255]}${e[i>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,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,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new h(e[0]);for(let s=1;s(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],i=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[i*a-r*n,r*o-s*a,s*n-i*o,0]},cross3Vec3(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return s[0]=r*l-o*a,s[1]=o*n-i*l,s[2]=i*a-r*n,s},sqLenVec4:e=>p.dotVec4(e,e),lenVec4:e=>Math.sqrt(p.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=>p.dotVec3(e,e),sqLenVec2:e=>p.dotVec2(e,e),lenVec3:e=>Math.sqrt(p.sqLenVec3(e)),distVec3:(()=>{const e=new h(3);return(t,s)=>p.lenVec3(p.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(p.sqLenVec2(e)),distVec2:(()=>{const e=new h(2);return(t,s)=>p.lenVec2(p.subVec2(t,s,e))})(),rcpVec3:(e,t)=>p.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/p.lenVec4(e);return p.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/p.lenVec3(e);return p.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/p.lenVec2(e);return p.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=p.dotVec3(e,t)/Math.sqrt(p.sqLenVec3(e)*p.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new h(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=p.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=p.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=p.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,i=(t=Array.prototype.slice.call(t)).length;s({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||p.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:()=>p.m4s(0),setMat4ToOnes:()=>p.m4s(1),diagonalMat4v:e=>new h([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,i)=>p.diagonalMat4v([e,t,s,i]),diagonalMat4s:e=>p.diagonalMat4c(e,e,e,e),identityMat4:(e=new h(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 h(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>p.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const i=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],h=e[6],c=e[7],A=e[8],u=e[9],p=e[10],d=e[11],f=e[12],m=e[13],E=e[14],y=e[15],g=t[0],v=t[1],I=t[2],_=t[3],T=t[4],R=t[5],P=t[6],D=t[7],b=t[8],C=t[9],N=t[10],O=t[11],S=t[12],x=t[13],w=t[14],B=t[15];return s[0]=g*i+v*a+I*A+_*f,s[1]=g*r+v*l+I*u+_*m,s[2]=g*o+v*h+I*p+_*E,s[3]=g*n+v*c+I*d+_*y,s[4]=T*i+R*a+P*A+D*f,s[5]=T*r+R*l+P*u+D*m,s[6]=T*o+R*h+P*p+D*E,s[7]=T*n+R*c+P*d+D*y,s[8]=b*i+C*a+N*A+O*f,s[9]=b*r+C*l+N*u+O*m,s[10]=b*o+C*h+N*p+O*E,s[11]=b*n+C*c+N*d+O*y,s[12]=S*i+x*a+w*A+B*f,s[13]=S*r+x*l+w*u+B*m,s[14]=S*o+x*h+w*p+B*E,s[15]=S*n+x*c+w*d+B*y,s},mulMat3(e,t,s){s||(s=new h(9));const i=e[0],r=e[3],o=e[6],n=e[1],a=e[4],l=e[7],c=e[2],A=e[5],u=e[8],p=t[0],d=t[3],f=t[6],m=t[1],E=t[4],y=t[7],g=t[2],v=t[5],I=t[8];return s[0]=i*p+r*m+o*g,s[3]=i*d+r*E+o*v,s[6]=i*f+r*y+o*I,s[1]=n*p+a*m+l*g,s[4]=n*d+a*E+l*v,s[7]=n*f+a*y+l*I,s[2]=c*p+A*m+u*g,s[5]=c*d+A*E+u*v,s[8]=c*f+A*y+u*I,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=p.vec4()){const i=t[0],r=t[1],o=t[2],n=t[3];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12]*n,s[1]=e[1]*i+e[5]*r+e[9]*o+e[13]*n,s[2]=e[2]*i+e[6]*r+e[10]*o+e[14]*n,s[3]=e[3]*i+e[7]*r+e[11]*o+e[15]*n,s},transposeMat4(e,t){const s=e[4],i=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],h=e[3],c=e[6],A=e[7],u=e[11];return e[1]=s,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=i,e[12]=h,e[13]=A,e[14]=u,e}return t[0]=e[0],t[1]=s,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]=i,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],i=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=i,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],s=e[1],i=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],h=e[8],c=e[9],A=e[10],u=e[11],p=e[12],d=e[13],f=e[14],m=e[15];return p*c*a*r-h*d*a*r-p*n*A*r+o*d*A*r+h*n*f*r-o*c*f*r-p*c*i*l+h*d*i*l+p*s*A*l-t*d*A*l-h*s*f*l+t*c*f*l+p*n*i*u-o*d*i*u-p*s*a*u+t*d*a*u+o*s*f*u-t*n*f*u-h*n*i*m+o*c*i*m+h*s*a*m-t*c*a*m-o*s*A*m+t*n*A*m},inverseMat4(e,t){t||(t=e);const s=e[0],i=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],h=e[7],c=e[8],A=e[9],u=e[10],p=e[11],d=e[12],f=e[13],m=e[14],E=e[15],y=s*a-i*n,g=s*l-r*n,v=s*h-o*n,I=i*l-r*a,_=i*h-o*a,T=r*h-o*l,R=c*f-A*d,P=c*m-u*d,D=c*E-p*d,b=A*m-u*f,C=A*E-p*f,N=u*E-p*m,O=1/(y*N-g*C+v*b+I*D-_*P+T*R);return t[0]=(a*N-l*C+h*b)*O,t[1]=(-i*N+r*C-o*b)*O,t[2]=(f*T-m*_+E*I)*O,t[3]=(-A*T+u*_-p*I)*O,t[4]=(-n*N+l*D-h*P)*O,t[5]=(s*N-r*D+o*P)*O,t[6]=(-d*T+m*v-E*g)*O,t[7]=(c*T-u*v+p*g)*O,t[8]=(n*C-a*D+h*R)*O,t[9]=(-s*C+i*D-o*R)*O,t[10]=(d*_-f*v+E*y)*O,t[11]=(-c*_+A*v-p*y)*O,t[12]=(-n*b+a*P-l*R)*O,t[13]=(s*b-i*P+r*R)*O,t[14]=(-d*I+f*g-m*y)*O,t[15]=(c*I-A*g+u*y)*O,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||p.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||p.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new h(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.translationMat4v(e,r))})(),translationMat4s:(e,t)=>p.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>p.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,i){const r=i[3];i[0]+=r*e,i[1]+=r*t,i[2]+=r*s;const o=i[7];i[4]+=o*e,i[5]+=o*t,i[6]+=o*s;const n=i[11];i[8]+=n*e,i[9]+=n*t,i[10]+=n*s;const a=i[15];return i[12]+=a*e,i[13]+=a*t,i[14]+=a*s,i},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const i=p.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=i[0],l=i[1],h=i[2];let c,A,u,d,f,m;return c=a*l,A=l*h,u=h*a,d=a*r,f=l*r,m=h*r,(s=s||p.mat4())[0]=n*a*a+o,s[1]=n*c+m,s[2]=n*u-f,s[3]=0,s[4]=n*c-m,s[5]=n*l*l+o,s[6]=n*A+d,s[7]=0,s[8]=n*u+f,s[9]=n*A-d,s[10]=n*h*h+o,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,i,r)=>p.rotationMat4v(e,[t,s,i],r),scalingMat4v:(e,t=p.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=p.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new h(3);return(t,s,i,r)=>(e[0]=t,e[1]=s,e[2]=i,p.scalingMat4v(e,r))})(),scaleMat4c:(e,t,s,i)=>(i[0]*=e,i[4]*=t,i[8]*=s,i[1]*=e,i[5]*=t,i[9]*=s,i[2]*=e,i[6]*=t,i[10]*=s,i[3]*=e,i[7]*=t,i[11]*=s,i),scaleMat4v(e,t){const s=e[0],i=e[1],r=e[2];return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,t},scalingMat4s:e=>p.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=p.mat4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=i+i,l=r+r,h=o+o,c=i*a,A=i*l,u=i*h,d=r*l,f=r*h,m=o*h,E=n*a,y=n*l,g=n*h;return s[0]=1-(d+m),s[1]=A+g,s[2]=u-y,s[3]=0,s[4]=A-g,s[5]=1-(c+m),s[6]=f+E,s[7]=0,s[8]=u+y,s[9]=f-E,s[10]=1-(c+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=p.vec4()){const i=p.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],h=e[9],c=e[2],A=e[6],u=e[10];return"XYZ"===t?(s[1]=Math.asin(i(n,-1,1)),Math.abs(n)<.99999?(s[0]=Math.atan2(-h,u),s[2]=Math.atan2(-o,r)):(s[0]=Math.atan2(A,l),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-i(h,-1,1)),Math.abs(h)<.99999?(s[1]=Math.atan2(n,u),s[2]=Math.atan2(a,l)):(s[1]=Math.atan2(-c,r),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(i(A,-1,1)),Math.abs(A)<.99999?(s[1]=Math.atan2(-c,u),s[2]=Math.atan2(-o,l)):(s[1]=0,s[2]=Math.atan2(a,r))):"ZYX"===t?(s[1]=Math.asin(-i(c,-1,1)),Math.abs(c)<.99999?(s[0]=Math.atan2(A,u),s[2]=Math.atan2(a,r)):(s[0]=0,s[2]=Math.atan2(-o,l))):"YZX"===t?(s[2]=Math.asin(i(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(-h,l),s[1]=Math.atan2(-c,r)):(s[0]=0,s[1]=Math.atan2(n,u))):"XZY"===t&&(s[2]=Math.asin(-i(o,-1,1)),Math.abs(o)<.99999?(s[0]=Math.atan2(A,l),s[1]=Math.atan2(n,r)):(s[0]=Math.atan2(-h,u),s[1]=0)),s},composeMat4:(e,t,s,i=p.mat4())=>(p.quaternionToRotationMat4(t,i),p.scaleMat4v(s,i),p.translateMat4v(e,i),i),decomposeMat4:(()=>{const e=new h(3),t=new h(16);return function(s,i,r,o){e[0]=s[0],e[1]=s[1],e[2]=s[2];let n=p.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const a=p.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const l=p.lenVec3(e);p.determinantMat4(s)<0&&(n=-n),i[0]=s[12],i[1]=s[13],i[2]=s[14],t.set(s);const h=1/n,c=1/a,A=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=A,t[9]*=A,t[10]*=A,p.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,i){i||(i=p.mat4());const r=e[0],o=e[1],n=e[2],a=s[0],l=s[1],h=s[2],c=t[0],A=t[1],u=t[2];if(r===c&&o===A&&n===u)return p.identityMat4();let d,f,m,E,y,g,v,I,_,T;return d=r-c,f=o-A,m=n-u,T=1/Math.sqrt(d*d+f*f+m*m),d*=T,f*=T,m*=T,E=l*m-h*f,y=h*d-a*m,g=a*f-l*d,T=Math.sqrt(E*E+y*y+g*g),T?(T=1/T,E*=T,y*=T,g*=T):(E=0,y=0,g=0),v=f*g-m*y,I=m*E-d*g,_=d*y-f*E,T=Math.sqrt(v*v+I*I+_*_),T?(T=1/T,v*=T,I*=T,_*=T):(v=0,I=0,_=0),i[0]=E,i[1]=v,i[2]=d,i[3]=0,i[4]=y,i[5]=I,i[6]=f,i[7]=0,i[8]=g,i[9]=_,i[10]=m,i[11]=0,i[12]=-(E*r+y*o+g*n),i[13]=-(v*r+I*o+_*n),i[14]=-(d*r+f*o+m*n),i[15]=1,i},lookAtMat4c:(e,t,s,i,r,o,n,a,l)=>p.lookAtMat4v([e,t,s],[i,r,o],[n,a,l],[]),orthoMat4c(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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/h,n[11]=0,n[12]=-(e+t)/a,n[13]=-(i+s)/l,n[14]=-(o+r)/h,n[15]=1,n},frustumMat4v(e,t,s){s||(s=p.mat4());const i=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];p.addVec4(r,i,c),p.subVec4(r,i,A);const o=2*i[2],n=A[0],a=A[1],l=A[2];return s[0]=o/n,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=o/a,s[6]=0,s[7]=0,s[8]=c[0]/n,s[9]=c[1]/a,s[10]=-c[2]/l,s[11]=-1,s[12]=0,s[13]=0,s[14]=-o*r[2]/l,s[15]=0,s},frustumMat4(e,t,s,i,r,o,n){n||(n=p.mat4());const a=t-e,l=i-s,h=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]=(i+s)/l,n[10]=-(o+r)/h,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/h,n[15]=0,n},perspectiveMat4(e,t,s,i,r){const o=[],n=[];return o[2]=s,n[2]=i,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],p.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,s=p.vec3()){const i=t[0],r=t[1],o=t[2];return s[0]=e[0]*i+e[4]*r+e[8]*o+e[12],s[1]=e[1]*i+e[5]*r+e[9]*o+e[13],s[2]=e[2]*i+e[6]*r+e[10]*o+e[14],s},transformPoint4:(e,t,s=p.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const i=s||[],r=t.length;let o,n,a,l;const h=e[0],c=e[1],A=e[2],u=e[3],p=e[4],d=e[5],f=e[6],m=e[7],E=e[8],y=e[9],g=e[10],v=e[11],I=e[12],_=e[13],T=e[14],R=e[15];let P;for(let e=0;e{const e=new h(16),t=new h(16),s=new h(16);return function(i,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),s),i,n)}})(),lerpVec3(e,t,s,i,r,o){const n=o||p.vec3(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n},lerpMat4(e,t,s,i,r,o){const n=o||p.mat4(),a=(e-t)/(s-t);return n[0]=i[0]+a*(r[0]-i[0]),n[1]=i[1]+a*(r[1]-i[1]),n[2]=i[2]+a*(r[2]-i[2]),n[3]=i[3]+a*(r[3]-i[3]),n[4]=i[4]+a*(r[4]-i[4]),n[5]=i[5]+a*(r[5]-i[5]),n[6]=i[6]+a*(r[6]-i[6]),n[7]=i[7]+a*(r[7]-i[7]),n[8]=i[8]+a*(r[8]-i[8]),n[9]=i[9]+a*(r[9]-i[9]),n[10]=i[10]+a*(r[10]-i[10]),n[11]=i[11]+a*(r[11]-i[11]),n[12]=i[12]+a*(r[12]-i[12]),n[13]=i[13]+a*(r[13]-i[13]),n[14]=i[14]+a*(r[14]-i[14]),n[15]=i[15]+a*(r[15]-i[15]),n},flatten(e){const t=[];let s,i,r,o,n;for(s=0,i=e.length;s(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=p.vec4()){const i=e[0]*p.DEGTORAD/2,r=e[1]*p.DEGTORAD/2,o=e[2]*p.DEGTORAD/2,n=Math.cos(i),a=Math.cos(r),l=Math.cos(o),h=Math.sin(i),c=Math.sin(r),A=Math.sin(o);return"XYZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"YXZ"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"ZXY"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l-h*c*A):"ZYX"===t?(s[0]=h*a*l-n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l+h*c*A):"YZX"===t?(s[0]=h*a*l+n*c*A,s[1]=n*c*l+h*a*A,s[2]=n*a*A-h*c*l,s[3]=n*a*l-h*c*A):"XZY"===t&&(s[0]=h*a*l-n*c*A,s[1]=n*c*l-h*a*A,s[2]=n*a*A+h*c*l,s[3]=n*a*l+h*c*A),s},mat4ToQuaternion(e,t=p.vec4()){const s=e[0],i=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],h=e[6],c=e[10];let A;const u=s+n+c;return u>0?(A=.5/Math.sqrt(u+1),t[3]=.25/A,t[0]=(h-a)*A,t[1]=(r-l)*A,t[2]=(o-i)*A):s>n&&s>c?(A=2*Math.sqrt(1+s-n-c),t[3]=(h-a)/A,t[0]=.25*A,t[1]=(i+o)/A,t[2]=(r+l)/A):n>c?(A=2*Math.sqrt(1+n-s-c),t[3]=(r-l)/A,t[0]=(i+o)/A,t[1]=.25*A,t[2]=(a+h)/A):(A=2*Math.sqrt(1+c-s-n),t[3]=(o-i)/A,t[0]=(r+l)/A,t[1]=(a+h)/A,t[2]=.25*A),t},vec3PairToQuaternion(e,t,s=p.vec4()){const i=Math.sqrt(p.dotVec3(e,e)*p.dotVec3(t,t));let r=i+p.dotVec3(e,t);return r<1e-8*i?(r=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):p.cross3Vec3(e,t,s),s[3]=r,p.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=p.vec4()){const s=e[3]/2,i=Math.sin(s);return t[0]=i*e[0],t[1]=i*e[1],t[2]=i*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new h(16);return(t,s,i)=>(i=i||p.vec3(),p.quaternionToRotationMat4(t,e),p.mat4ToEuler(e,s,i),i)})(),mulQuaternions(e,t,s=p.vec4()){const i=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],h=t[2],c=t[3];return s[0]=n*a+i*c+r*h-o*l,s[1]=n*l+r*c+o*a-i*h,s[2]=n*h+o*c+i*l-r*a,s[3]=n*c-i*a-r*l-o*h,s},vec3ApplyQuaternion(e,t,s=p.vec3()){const i=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],h=e[3],c=h*i+a*o-l*r,A=h*r+l*i-n*o,u=h*o+n*r-a*i,d=-n*i-a*r-l*o;return s[0]=c*h+d*-n+A*-l-u*-a,s[1]=A*h+d*-a+u*-n-c*-l,s[2]=u*h+d*-l+c*-a-A*-n,s},quaternionToMat4(e,t){t=p.identityMat4(t);const s=e[0],i=e[1],r=e[2],o=e[3],n=2*s,a=2*i,l=2*r,h=n*o,c=a*o,A=l*o,u=n*s,d=a*s,f=l*s,m=a*i,E=l*i,y=l*r;return t[0]=1-(m+y),t[1]=d+A,t[2]=f-c,t[4]=d-A,t[5]=1-(u+y),t[6]=E+h,t[8]=f+c,t[9]=E-h,t[10]=1-(u+m),t},quaternionToRotationMat4(e,t){const s=e[0],i=e[1],r=e[2],o=e[3],n=s+s,a=i+i,l=r+r,h=s*n,c=s*a,A=s*l,u=i*a,p=i*l,d=r*l,f=o*n,m=o*a,E=o*l;return t[0]=1-(u+d),t[4]=c-E,t[8]=A+m,t[1]=c+E,t[5]=1-(h+d),t[9]=p-f,t[2]=A-m,t[6]=p+f,t[10]=1-(h+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=p.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>p.normalizeQuaternion(p.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=p.vec4()){const s=(e=p.normalizeQuaternion(e,u))[3],i=2*Math.acos(s),r=Math.sqrt(1-s*s);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]=i,t},AABB3:e=>new h(e||6),AABB2:e=>new h(e||4),OBB3:e=>new h(e||32),OBB2:e=>new h(e||16),Sphere3:(e,t,s,i)=>new h([e,t,s,i]),transformOBB3(e,t,s=t){let i;const r=t.length;let o,n,a;const l=e[0],h=e[1],c=e[2],A=e[3],u=e[4],p=e[5],d=e[6],f=e[7],m=e[8],E=e[9],y=e[10],g=e[11],v=e[12],I=e[13],_=e[14],T=e[15];for(i=0;i{const e=new h(3),t=new h(3),s=new h(3);return i=>(e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5],p.subVec3(t,e,s),Math.abs(p.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new h(3),t=new h(3),s=new h(3);return(i,r)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],t[0]=i[3],t[1]=i[4],t[2]=i[5];const o=p.subVec3(t,e,s),n=r[0]-i[0],a=i[3]-r[0],l=r[1]-i[1],h=i[4]-r[1],c=r[2]-i[2],A=i[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>h?l:h,o[2]+=c>A?c:A,Math.abs(p.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||p.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||p.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=p.AABB3())=>(e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MAX_DOUBLE,e[3]=p.MIN_DOUBLE,e[4]=p.MIN_DOUBLE,e[5]=p.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=p.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 h(3);return(t,s,i)=>{s=s||p.AABB3();let r,o,n,a=p.MAX_DOUBLE,l=p.MAX_DOUBLE,h=p.MAX_DOUBLE,c=p.MIN_DOUBLE,A=p.MIN_DOUBLE,u=p.MIN_DOUBLE;for(let s=0,d=t.length;sc&&(c=r),o>A&&(A=o),n>u&&(u=n);return s[0]=a,s[1]=l,s[2]=h,s[3]=c,s[4]=A,s[5]=u,s}})(),OBB3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=p.AABB3()){let s,i,r,o=p.MAX_DOUBLE,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE,c=p.MIN_DOUBLE;for(let t=0,A=e.length;tl&&(l=s),i>h&&(h=i),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new h(3);return(t,s)=>{s=s||p.vec4();let i,r=0,o=0,n=0;const a=t.length;for(i=0;ih&&(h=l);return s[3]=h,s}})(),positions3ToSphere3:(()=>{const e=new h(3),t=new h(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length;let h=0;for(r=0;rh&&(h=A);return i[3]=h,i}})(),OBB3ToSphere3:(()=>{const e=new h(3),t=new h(3);return(s,i)=>{i=i||p.vec4();let r,o=0,n=0,a=0;const l=s.length,h=l/4;for(r=0;rA&&(A=c);return i[3]=A,i}})(),getSphere3Center:(e,t=p.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=p.vec3()){let s=0,i=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]s&&(e[0]=s),e[1]>i&&(e[1]=i),e[2]>r&&(e[2]=r),e[3](e[0]=p.MAX_DOUBLE,e[1]=p.MAX_DOUBLE,e[2]=p.MIN_DOUBLE,e[3]=p.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(i=e[0]*s[0],r=e[0]*s[3]):(i=e[0]*s[3],r=e[0]*s[0]),e[1]>0?(i+=e[1]*s[1],r+=e[1]*s[4]):(i+=e[1]*s[4],r+=e[1]*s[1]),e[2]>0?(i+=e[2]*s[2],r+=e[2]*s[5]):(i+=e[2]*s[5],r+=e[2]*s[2]);if(i<=-t&&r<=-t)return-1;return i>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=p.AABB2()){let s,i,r,o,n=p.MAX_DOUBLE,a=p.MAX_DOUBLE,l=p.MIN_DOUBLE,h=p.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=s),i>h&&(h=i);return t[0]=n,t[1]=a,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(s-t)+2*e*(i-s),tangentQuadraticBezier3:(e,t,s,i,r)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*i*(1-e)-3*e*e*i+3*e*e*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,s,i,r){const o=.5*(s-e),n=.5*(i-t),a=r*r;return(2*t-2*s+o+n)*(r*a)+(-3*t+3*s-2*o-n)*a+o*r+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,i){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,i)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,i,r){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,i)+this.b3p3(e,r)},triangleNormal(e,t,s,i=p.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=s[0]-e[0],l=s[1]-e[1],h=s[2]-e[2],c=o*h-n*l,A=n*a-r*h,u=r*l-o*a,d=Math.sqrt(c*c+A*A+u*u);return 0===d?(i[0]=0,i[1]=0,i[2]=0):(i[0]=c/d,i[1]=A/d,i[2]=u/d),i},rayTriangleIntersect:(()=>{const e=new h(3),t=new h(3),s=new h(3),i=new h(3),r=new h(3);return(o,n,a,l,h,c)=>{c=c||p.vec3();const A=p.subVec3(l,a,e),u=p.subVec3(h,a,t),d=p.cross3Vec3(n,u,s),f=p.dotVec3(A,d);if(f<1e-6)return null;const m=p.subVec3(o,a,i),E=p.dotVec3(m,d);if(E<0||E>f)return null;const y=p.cross3Vec3(m,A,r),g=p.dotVec3(n,y);if(g<0||E+g>f)return null;const v=p.dotVec3(u,y)/f;return c[0]=o[0]+v*n[0],c[1]=o[1]+v*n[1],c[2]=o[2]+v*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new h(3),t=new h(3),s=new h(3),i=new h(3);return(r,o,n,a,l,h)=>{h=h||p.vec3(),o=p.normalizeVec3(o,e);const c=p.subVec3(a,n,t),A=p.subVec3(l,n,s),u=p.cross3Vec3(c,A,i);p.normalizeVec3(u,u);const d=-p.dotVec3(n,u),f=-(p.dotVec3(r,u)+d)/p.dotVec3(o,u);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new h(3),t=new h(3),s=new h(3);return(i,r,o,n,a)=>{const l=p.subVec3(n,r,e),h=p.subVec3(o,r,t),c=p.subVec3(i,r,s),A=p.dotVec3(l,l),u=p.dotVec3(l,h),d=p.dotVec3(l,c),f=p.dotVec3(h,h),m=p.dotVec3(h,c),E=A*f-u*u;if(0===E)return null;const y=1/E,g=(f*d-u*m)*y,v=(A*m-u*d)*y;return a[0]=1-g-v,a[1]=v,a[2]=g,a}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,i,r=p.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+s[0]*n+i[0]*a,r[1]=t[1]*o+s[1]*n+i[1]*a,r[2]=t[2]*o+s[2]*n+i[2]*a,r},mergeVertices(e,t,s,i){const r={},o=[],n=[],a=t?[]:null,l=s?[]:null,h=[];let c,A,u,p;const d=1e4;let f,m,E=0;for(f=0,m=e.length;f{const e=new h(3),t=new h(3),s=new h(3),i=new h(3),r=new h(3),o=new h(3);return(n,a,l)=>{let h,c;const A=new Array(n.length/3);let u,d,f,m,E,y,g;for(h=0,c=a.length;h{const e=new h(3),t=new h(3),s=new h(3),i=new h(3),r=new h(3),o=new h(3),n=new h(3);return(a,l,h)=>{const c=new Float32Array(a.length);for(let A=0;A>24&255,c=u>>16&255,h=u>>8&255,l=255&u,a=t[s],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+1],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,a=t[s+2],n=3*a,r[p++]=e[n],r[p++]=e[n+1],r[p++]=e[n+2],o[d++]=l,o[d++]=h,o[d++]=c,o[d++]=A,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,s={}){const i=s.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,h,c,A;const u=1e4;let d,f,m,E,y,g;for(f=0,E=e.length;f{const e=new h(4),t=new h(4);return(s,i,r,o,n)=>{e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=1,p.transformVec4(s,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],p.transformVec3(s,e,t),p.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new h(16),t=new h(16),s=new h(4),i=new h(4),r=new h(4),o=new h(4);return(n,a,l,h,c,A)=>{const u=p.mulMat4(l,a,e),d=p.inverseMat4(u,t),f=n.width,m=n.height,E=(h[0]-f/2)/(f/2),y=-(h[1]-m/2)/(m/2);s[0]=E,s[1]=y,s[2]=-1,s[3]=1,p.transformVec4(d,s,i),p.mulVec4Scalar(i,1/i[3]),r[0]=E,r[1]=y,r[2]=1,r[3]=1,p.transformVec4(d,r,o),p.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],p.subVec3(o,i,A),p.normalizeVec3(A)}})(),canvasPosToLocalRay:(()=>{const e=new h(3),t=new h(3);return(s,i,r,o,n,a,l)=>{p.canvasPosToWorldRay(s,i,r,n,e,t),p.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new h(16),t=new h(4),s=new h(4);return(i,r,o,n,a)=>{const l=p.inverseMat4(i,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,p.transformVec4(l,t,s),n[0]=s[0],n[1]=s[1],n[2]=s[2],p.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,i,r,o){const n=new h(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let l,c;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,l=0,c=s.length;ln[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(s.length<20||o>10)return a.triangles=s,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 p=(n[u]+n[u+3])/2,d=new Array(s.length);let f=0;const m=new Array(s.length);let E=0;for(l=0,c=s.length;l{const i=e.length/3,r=new Array(i);for(let e=0;e=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t}};p.buildEdgeIndices=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),i=s+e[1],r=s;r{};t=t||i,s=s||i;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var i=e.target.response;if(200===this.status){var r;try{r=JSON.parse(i)}catch(e){s(`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(i))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),r.addEventListener("error",(function(e){s(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,s){var i=e=>{};t=t||i,s=s||i;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),s=new Uint8Array(e);for(var n=0;n=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}},_={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let R,P=0,D=0;const b=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(b.scenes[e.id])return void console.error(`[ERROR] Scene ${y.inQuotes(e.id)} already exists`)}else e.id=v.addItem({});b.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;g[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{v.removeItem(e.id),delete b.scenes[e.id],delete g[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in b.scenes)b.scenes.hasOwnProperty(t)&&(e=b.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete b.scenes[e.id]))},this.scheduleTask=function(e,t){I.push(e),I.push(t)},this.runTasks=function(e=-1){let t,s,i=(new Date).getTime(),r=0;for(;I.length>0&&(e<0||i0&&R>0){var t=1e3/R;D+=t,T.push(t),T.length>=30&&(D-=T.shift()),d.frame.fps=Math.round(D/T.length)}!function(e){const t=b.runTasks(e+10),s=b.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in _.time=e,b.scenes)if(b.scenes.hasOwnProperty(t)){var s=b.scenes[t];_.sceneId=t,_.startTime=s.startTime,_.deltaTime=null!=_.prevTime?_.time-_.prevTime:0,s.fire("tick",_,!0)}_.prevTime=e}(e),function(){const e=b.scenes,t=!1;let s,i,r,o,n;for(n in e)e.hasOwnProperty(n)&&(s=e[n],i=g[n],i||(i=g[n]={}),r=s.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==r&&(i.ticksPerOcclusionTest=r,i.renderCountdown=r),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=r),o=s.ticksPerRender,i.ticksPerRender!==o&&(i.ticksPerRender=o,i.renderCountdown=o),0==--i.renderCountdown&&(s.render(t),i.renderCountdown=o))}(),P=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C);class N{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 N))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];let r;if(i)for(const s in i)i.hasOwnProperty(s)&&(r=i[s],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(e,s,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new t),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);const o=this._subIdMap.addItem();r[o]={callback:s,scope:i||this},this._subIdEvents[o]=e;const n=this._events[e];return void 0!==n&&s.call(i||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 s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const i=this,r=this.on(e,(function(e){i.off(r),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+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 s=e.component;const i=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(s&&(y.isNumeric(s)||y.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+y.inQuotes(e))}if(!s)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===i&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+y.inQuotes(s.id));if(o&&!s.isType(o))return void this.error("Expected a "+o+" type or subtype: "+s.type+" "+y.inQuotes(s.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,A;if(l){if(s&&l.id===s.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,A=h.length;c{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():b.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,i,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],s=t.component,i=t.subs,r=0,o=i.length;r0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let i=255;if(t){if(e<0?e=0:e>1&&(e=1),i=Math.floor(255*e),s===i)return}else if(i=255,s===i)return;for(let e=0,t=this.meshes.length;e{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&&(p.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){Y.set(this._viewPos),Y[3]=1,p.transformPoint4(this.scene.camera.projMatrix,Y,X);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+X[0]/X[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-X[1]/X[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 K?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]),x(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 q{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6;var s=this._wire,i=s.style;i.border="solid "+this._thickness+"px "+this._color,i.position="absolute",i["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,i.width="0px",i.height="0px",i.visibility="visible",i.top="0px",i.left="0px",i["-webkit-transform-origin"]="0 0",i["-moz-transform-origin"]="0 0",i["-ms-transform-origin"]="0 0",i["-o-transform-origin"]="0 0",i["transform-origin"]="0 0",i["-webkit-transform"]="rotate(0deg)",i["-moz-transform"]="rotate(0deg)",i["-ms-transform"]="rotate(0deg)",i["-o-transform"]="rotate(0deg)",i.transform="rotate(0deg)",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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.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,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var i=this._wireClickable.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,i){this._x1=e,this._y1=t,this._x2=s,this._y2=i,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){e=!!e,this._visible!==e&&(this._wire.style.visibility=e?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class J{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable";var s=this._dot,i=s.style;i["border-radius"]="25px",i.border="solid 2px white",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,i.width="8px",i.height="8px",i.visibility=!1!==t.visible?"visible":"hidden",i.top="0px",i.left="0px",i["box-shadow"]="0 2px 5px 0 #182A3D;",i.opacity=1,i["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var 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),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.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 s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var i=this._dotClickable.style;i.left=Math.round(e)-9+"px",i.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ${constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,i=s.style;i["border-radius"]="5px",i.color="white",i.padding="4px",i.border="solid 1px",i.background="lightgreen",i.position="absolute",i["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,i.width="auto",i.height="auto",i.visibility="visible",i.top="0px",i.left="0px",i["pointer-events"]="all",i.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,i){var r=e+.5*(s-e),o=t+.5*(i-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,s,i,r,o){var n=(e+s+r)/3,a=(t+i+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 ee=p.vec3(),te=p.vec3();class se extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new Z(s,t.origin),this._cornerMarker=new Z(s,t.corner),this._targetMarker=new Z(s,t.target),this._originWorld=p.vec3(),this._cornerWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._cornerDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._originWire=new q(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetWire=new q(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._angleLabel=new $(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,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=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._cpDirty){const u=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],m=this._targetMarker.viewPos[2];if(d>u||f>u||m>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);p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,i=e.canvas.canvas.getBoundingClientRect();const E=this._container.getBoundingClientRect();for(var r=i.top-E.top,o=i.left-E.left,n=e.canvas.boundary,a=n[2],l=n[3],h=0,c=0,A=t.length;c{switch(e.snappedToVertex||e.snappedToEdge?(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(i&&(i.visible=!0,i.centerPos=e.cursorPos||e.canvasPos,i.cursorPos=e.canvasPos,i.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red"),r=!0,o=e.entity,l.set(e.worldPos),h.set(e.canvasPos),this._mouseState){case 0:this.markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this.markerDiv.style.marginTop=e.canvasPos[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(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,i&&(i.visible=!0,i.centerPos=e.cursorPos,i.cursorPos=e.cursorPos,i.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class oe extends a{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 re(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,s=e.corner,i=e.target,r=new se(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:i.entity,worldPos:i.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]})),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,s]of Object.entries(this.measurements))s.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,s=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,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const ae=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class le extends N{constructor(e,t={}){super(e,t),this._backgroundColor=p.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let i=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(i=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{i&&(i=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new ne(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-"+p.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),i=s.style;i.height="100%",i.width="100%",i.padding="0",i.margin="0",i.background="rgba(0,0,0,0);",i.float="left",i.left="0",i.top="0",i.position="absolute",i.opacity="1.0",i["z-index"]="-10000",s.innerHTML+='',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?ce.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?ce.FS_MAX_FLOAT_PRECISION="mediump":ce.FS_MAX_FLOAT_PRECISION="lowp":ce.FS_MAX_FLOAT_PRECISION="mediump",ce.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),ce.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),ce.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),ce.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),ce.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ce.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),ce.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),ce.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),ce.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),ce.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){ce.SUPPORTED_EXTENSIONS[e]=!0})))}class ue{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class pe{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),i=[];for(let e=0;e0&&"/"===s.charAt(i+1)&&(s=s.substring(0,i)),t.push(s);return t.join("\n")}function ye(e){console.error(e.join("\n"))}class ge{constructor(e,t){this.id=me.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 pe(e,e.VERTEX_SHADER,Ee(this.source.vertex)),this._fragmentShader=new pe(e,e.FRAGMENT_SHADER,Ee(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void ye(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void ye(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void ye(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void ye(this.errors);let t,s,i,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 ye(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;sthis.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 Ie{constructor(e,t){this.scene=e,this.aabb=p.AABB3(),this.origin=p.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){s._setVisible(!1);continue}const n=s.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>i||l-10>r?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[o++]=a,this.pixels[o++]=l):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new Ie(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let i=this._occlusionLayers[s];i||(i=new Ie(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// OcclusionTester fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),i.push("}"),i}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new ge(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e0){const e=i.sectionPlanes;for(let i=0;i{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(i.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,i=this._scene,r=i.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=i.camera.project._state,l=a.near,h=a.far,c=a.matrix,A=this._getInverseProjectMat(),u=Math.random(),d="perspective"===i.camera.projection;Pe[0]=o,Pe[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),s.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,A),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,r.scale*(h/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,Pe),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new ge(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const i=new Float32Array([1,1,0,1,0,0,1,0]),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 ve(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),this._uvBuf=new ve(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW),this._indicesBuf=new ve(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const be=new Float32Array(we(17,[0,1])),Ce=new Float32Array(we(17,[1,0])),Ne=new Float32Array(function(e,t){const s=[];for(let i=0;i<=e;i++)s.push(xe(i,t));return s}(17,4)),Oe=new Float32Array(2);class Se{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 ge(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),i=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new ve(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new ve(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ve(e,e.ELEMENT_ARRAY_BUFFER,i,i.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=p.mat4();return()=>(e&&p.inverseMat4(o.camera.projMatrix,t),t)})());const i=this._scene.canvas.gl,r=this._program,o=this._scene,n=i.drawingBufferWidth,a=i.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;i.viewport(0,0,n,a),i.clearColor(0,0,0,1),i.enable(i.DEPTH_TEST),i.disable(i.BLEND),i.frontFace(i.CCW),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT),r.bind(),Oe[0]=n,Oe[1]=a,i.uniform2fv(this._uViewport,Oe),i.uniform1f(this._uCameraNear,h),i.uniform1f(this._uCameraFar,c),i.uniform1f(this._uDepthCutoff,.01),0===s?i.uniform2fv(this._uSampleOffsets,Ce):i.uniform2fv(this._uSampleOffsets,be),i.uniform1fv(this._uSampleWeights,Ne);const A=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,A,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),i.drawElements(i.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function xe(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function we(e,t){const s=[];for(let i=0;i<=e;i++)s.push(t[0]*i),s.push(t[1]*i);return s}class Be{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(e=null){if(this._touch(e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(e=null){let t,s;const i=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=i.drawingBufferWidth,s=i.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const r=i.createTexture();let o;i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e?i.texStorage2D(i.TEXTURE_2D,1,e,t,s):i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,s,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(o=i.createTexture(),i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT32F,t,s,0,i.DEPTH_COMPONENT,i.FLOAT,null));const n=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,n),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT32F,t,s);const a=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,a),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,o,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,n),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const l=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(l){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r,depthTexture:o,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,i=null,r=Uint8Array,o=4){const n=e,a=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,l=new r(o),h=this.gl;return h.readPixels(n,a,1,1,s||h.RGBA,i||h.UNSIGNED_BYTE,l,0),l}readArray(e=null,t=null,s=Uint8Array,i=4){const r=new s(this.buffer.width*this.buffer.height*i),o=this.gl;return o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,r,0),r}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,i=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,h=4*n,c=new Uint8Array(4*n);for(let e=0;e0)for(i.withSAO=!0,x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||j>0||U>0||H>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)),i.backfaces=!1,a||o.depthMask(!1),(U>0||H>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),H>0)for(x=0;x0)for(x=0;x0)for(x=0;x0)for(x=0;x0||W>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),W>0)for(x=0;x0)for(x=0;x0||K>0||Q>0){if(i.lastProgramId=null,e.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),K>0)for(x=0;x0)for(x=0;x0||X>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(x=0;x0)for(x=0;x0||q>0){if(i.lastProgramId=null,e.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),q>0)for(x=0;x0)for(x=0;x0){const t=Math.floor(e/4),s=l.size[0],i=t%s-Math.floor(s/2),o=Math.floor(t/s)-Math.floor(s/2),a=Math.sqrt(Math.pow(i,2)+Math.pow(o,2));y.push({x:i,y:o,dist:a,isVertex:r&&n?d[e+3]>p.length/2:r,result:[d[e+0],d[e+1],d[e+2],d[e+3]]})}let g=null,v=null;if(y.length>0){y.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),v=y[0].isVertex?"vertex":"edge",y=y[0].result;const e=p[y[3]],t=e.origin,s=e.coordinateScale;g=[y[0]*s[0]+t[0],y[1]*s[1]+t[1],y[2]*s[2]+t[2]]}if(null===f&&null==g)return null;let _=null;return null!==g&&(_=e.camera.projectWorldPos(g)),{snapType:v,snappedToVertex:"vertex"===v,snappedToEdge:"edge"===v,worldPos:f,snappedWorldPos:g,snappedCanvasPos:_}},this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new Re(e,I),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){P(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.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 h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,s=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()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=(e,t)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",s,!0)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(i=>{e>=i[0]-s&&e<=i[0]+s&&t>=i[1]-s&&t<=i[1]+s&&this.fire("mouseclicked",i,!0)}))}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,i=0;for(;t.offsetParent;)s+=t.offsetLeft,i+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-i}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 He=new t({});class Ge{constructor(e){this.id=He.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){He.removeItem(this.id)}}class Ve extends N{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Ge({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],s=e[3];this._state.boundary=[0,0,t,s],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class ke extends N{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],s=this._fovAxis;let i=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(i/=t),i=Math.min(i,120),p.perspectiveMat4(i*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class je extends N{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.canvas.boundary,i=s[2],r=s[3],o=i/r;let n,a,l,h;i>r?(n=-t,a=t,l=t/o,h=-t/o):(n=-t*o,a=t*o,l=t,h=-t),p.orthoMat4c(n,a,h,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class Qe extends N{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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(){p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class We extends N{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Ge({matrix:p.mat4(),inverseMatrix:p.mat4(),transposedMatrix:p.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&&(p.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(p.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,i,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return s[0]=(e[0]-n)/n,s[1]=(e[1]-a)/a,s[2]=t,s[3]=1,p.mulMat4v4(this.inverseMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1,p.mulMat4v4(this.camera.inverseViewMatrix,i,r),r}destroy(){super.destroy(),this._state.destroy()}}const ze=p.vec3(),Ke=p.vec3(),Ye=p.vec3(),Xe=p.vec3(),Ze=p.vec3(),qe=p.vec3(),Je=p.vec4(),$e=p.vec4(),et=p.vec4(),tt=p.mat4(),st=p.mat4(),it=p.vec3(),rt=p.vec3(),ot=p.vec3(),nt=p.vec3();class at extends N{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Ge({deviceMatrix:p.mat4(),hasDeviceMatrix:!1,matrix:p.mat4(),normalMatrix:p.mat4(),inverseMatrix:p.mat4()}),this._perspective=new ke(this),this._ortho=new je(this),this._frustum=new Qe(this),this._customProjection=new We(this),this._project=this._perspective,this._eye=p.vec3([0,0,10]),this._look=p.vec3([0,0,0]),this._up=p.vec3([0,1,0]),this._worldUp=p.vec3([0,1,0]),this._worldRight=p.vec3([1,0,0]),this._worldForward=p.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?(p.subVec3(this._eye,this._look,it),p.normalizeVec3(it,rt),p.mulVec3Scalar(rt,1e3,ot),p.addVec3(this._look,ot,nt),t=nt):t=this._eye,e.hasDeviceMatrix?(p.lookAtMat4v(t,this._look,this._up,st),p.mulMat4(e.deviceMatrix,st,e.matrix)):p.lookAtMat4v(t,this._look,this._up,e.matrix),p.inverseMat4(this._state.matrix,this._state.inverseMatrix),p.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=p.subVec3(this._eye,this._look,ze);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tt),t=p.transformPoint3(tt,t,Ke),this.eye=p.addVec3(this._look,t,Ye),this.up=p.transformPoint3(tt,this._up,Xe)}orbitPitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._eye,this._look,ze);const s=p.cross3Vec3(p.normalizeVec3(t,Ke),p.normalizeVec3(this._up,Ye));p.rotationMat4v(.0174532925*e,s,tt),t=p.transformPoint3(tt,t,Xe),this.up=p.transformPoint3(tt,this._up,Ze),this.eye=p.addVec3(t,this._look,qe)}yaw(e){let t=p.subVec3(this._look,this._eye,ze);p.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,tt),t=p.transformPoint3(tt,t,Ke),this.look=p.addVec3(t,this._eye,Ye),this._gimbalLock&&(this.up=p.transformPoint3(tt,this._up,Xe))}pitch(e){if(this._constrainPitch&&(e=p.dotVec3(this._up,this._worldUp)/p.DEGTORAD)<1)return;let t=p.subVec3(this._look,this._eye,ze);const s=p.cross3Vec3(p.normalizeVec3(t,Ke),p.normalizeVec3(this._up,Ye));p.rotationMat4v(.0174532925*e,s,tt),this.up=p.transformPoint3(tt,this._up,qe),t=p.transformPoint3(tt,t,Xe),this.look=p.addVec3(t,this._eye,Ze)}pan(e){const t=p.subVec3(this._eye,this._look,ze),s=[0,0,0];let i;if(0!==e[0]){const r=p.cross3Vec3(p.normalizeVec3(t,[]),p.normalizeVec3(this._up,Ke));i=p.mulVec3Scalar(r,e[0]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]}0!==e[1]&&(i=p.mulVec3Scalar(p.normalizeVec3(this._up,Ye),e[1]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),0!==e[2]&&(i=p.mulVec3Scalar(p.normalizeVec3(t,Xe),e[2]),s[0]+=i[0],s[1]+=i[1],s[2]+=i[2]),this.eye=p.addVec3(this._eye,s,Ze),this.look=p.addVec3(this._look,s,qe)}zoom(e){const t=p.subVec3(this._eye,this._look,ze),s=Math.abs(p.lenVec3(t,Ke)),i=Math.abs(s+e);if(i<.5)return;const r=p.normalizeVec3(t,Ye);this.eye=p.addVec3(this._look,p.mulVec3Scalar(r,i),Xe)}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=p.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 p.lenVec3(p.subVec3(this._look,this._eye,ze))}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=Je,s=$e,i=et;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,p.mulMat4v4(this.viewMatrix,t,s),p.mulMat4v4(this.projMatrix,s,i),p.mulVec3Scalar(i,1/i[3]),i[3]=1,i[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[i[0]*o+o,i[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class lt extends N{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class ht extends lt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Ge({type:"dir",dir:p.vec3([1,1,1]),color:p.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=p.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,i=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],r=[0,1,0];p.lookAtMat4v(i,s,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=p.identityMat4()),p.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Be(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 ct extends lt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:p.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 At extends N{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var ut=function(){const e=[],t=[],s=[],i=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3();return function(E,y,g,v){!function(r,o){const n={};let a,l,h,c;const A=Math.pow(10,4);let u,p,d=0;for(u=0,p=r.length;u_)||(w=s[N.index1],B=s[N.index2],(!M&&w>65535||B>65535)&&(M=!0),I.push(w),I.push(B));return M?new Uint32Array(I):new Uint16Array(I)}}();const pt=function(){const e=p.mat4(),t=p.mat4();return function(s,i){i=i||p.mat4();const r=s[0],o=s[1],n=s[2],a=s[3]-r,l=s[4]-o,h=s[5]-n,c=65535;return p.identityMat4(e),p.translationMat4v(s,e),p.identityMat4(t),p.scalingMat4v([a/c,l/c,h/c],t),p.mulMat4(e,t,i),i}}();var dt=function(){const e=p.mat4(),t=p.mat4();return function(s,i,r){const o=new Uint16Array(s.length),n=new Float32Array([r[0]!==i[0]?65535/(r[0]-i[0]):0,r[1]!==i[1]?65535/(r[1]-i[1]):0,r[2]!==i[2]?65535/(r[2]-i[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[s](127.5*r+(r<0?-1:0)),Math[i](127.5*o+(o<0?-1:0))])}function Et(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}function yt(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const gt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let i,r;for(i=0;i<3;i++)t[i]=Number.MAX_VALUE,s[i]=-Number.MAX_VALUE;for(i=0;in&&(r=s,n=o),s=mt(e,a,"floor","ceil"),i=Et(s),o=yt(e,a,i),o>n&&(r=s,n=o),s=mt(e,a,"ceil","ceil"),i=Et(s),o=yt(e,a,i),o>n&&(r=s,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let s=0,i=0,r=e.length;s=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[i+0]=r/a,t[i+1]=o/a,t[i+2]=n/a,i+=3}return t},decompressNormal:function(e,t){let s=e[0],i=e[1];s=(2*s+1)/255,i=(2*i+1)/255;const r=1-Math.abs(s)-Math.abs(i);r<0&&(s=(1-Math.abs(i))*(s>=0?1:-1),i=(1-Math.abs(s))*(i>=0?1:-1));const o=Math.sqrt(s*s+i*i+r*r);return t[0]=s/o,t[1]=i/o,t[2]=r/o,t}},vt=d.memory,It=p.AABB3();class _t extends At{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ge({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=gt.getPositionsBounds(t.positions),i=gt.compressPositions(t.positions,e.min,e.max);s.positions=i.quantized,s.positionsDecodeMatrix=i.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=gt.getUVBounds(t.uv),i=gt.compressUVs(t.uv,e.min,e.max);s.uv=i.quantized,s.uvDecodeMatrix=i.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=gt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),vt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),vt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ve(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),vt.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new ve(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),vt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ve(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),vt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ve(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),vt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=ut(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),vt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=p.buildPickTriangles(e.positions,e.indices,e.compressGeometry),i=s.positions,r=s.colors;this._pickTrianglePositionsBuf=new ve(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),vt.positions+=this._pickTrianglePositionsBuf.numItems,vt.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),gt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=gt.getPositionsBounds(e),i=gt.compressPositions(e,s.min,s.max);e=i.quantized,t.positionsDecodeMatrix=i.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),gt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),gt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=p.AABB3()),p.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=p.OBB3()),p.positions3ToAABB3(this._state.positions,It,this._state.positionsDecodeMatrix),p.AABB3ToOBB3(It,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(),vt.meshes--}}function Tt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,h=-s+n,c=-i+a,A=t+o,u=s+n,p=i+a;return y.apply(e,{positions:[A,u,p,l,u,p,l,h,p,A,h,p,A,u,p,A,h,p,A,h,c,A,u,c,A,u,p,A,u,c,l,u,c,l,u,p,l,u,p,l,u,c,l,h,c,l,h,p,l,h,c,A,h,c,A,h,p,l,h,p,A,h,c,l,h,c,l,u,c,A,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Rt extends N{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const Pt={opaque:0,mask:1,blend:2},Dt=["opaque","mask","blend"];class bt extends Rt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Ge({type:"PhongMaterial",ambient:p.vec3([1,1,1]),diffuse:p.vec3([1,1,1]),specular:p.vec3([1,1,1]),emissive:p.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=Pt[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 Dt[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 Ct={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Nt extends Rt{get type(){return"EmphasisMaterial"}get presets(){return Ct}constructor(e,t={}){super(e,t),this._state=new Ge({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=Ct[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(Ct).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Ot={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 St extends Rt{get type(){return"EdgeMaterial"}get presets(){return Ot}constructor(e,t={}){super(e,t),this._state=new Ge({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=Ot[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(Ot).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const xt={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 wt extends N{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=p.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return xt}set units(e){e||(e="meters");xt[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=p.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=p.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 Bt extends N{constructor(e,t={}){super(e,t),this._supported=ce.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 Mt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Ft extends Rt{get type(){return"PointsMaterial"}get presets(){return Mt}constructor(e,t={}){super(e,t),this._state=new Ge({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=Mt[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(Mt).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 Lt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Ut extends Rt{get type(){return"LinesMaterial"}get presets(){return Lt}constructor(e,t={}){super(e,t),this._state=new Ge({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=Lt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Lt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ht(e,t){const s={};let i,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Le(this,{transparent:i,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,i=t.length;e0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),i=null,s=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=p.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const i=this.types[s];i&&(delete i[t],y.isEmptyObject(i)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&b.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,i=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),h=!0}h||(t=-100,s=-100,i=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=i,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 s=e.includeEntities||e.include;s&&(e.includeEntityIds=Ht(this,s));const i=e.excludeEntities||e.exclude;return i&&(e.excludeEntityIds=Ht(this,i)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t{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=p.AABB3();return e[0]=s,e[1]=i,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 s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let s=!1;for(let i=0,r=e.length;i0,l=!!r.compressGeometry,h=[];h.push("#version 300 es"),h.push("// Lambertian drawing vertex shader"),h.push("in vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("out float vFragDepth;"),h.push("bool isPerspectiveMatrix(mat4 m) {"),h.push(" return (m[2][3] == - 1.0);"),h.push("}"),h.push("out float isPerspective;"));a&&h.push("out vec4 vWorldPosition;");if(h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("in vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.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);"),h.push(" }"),h.push(" return normalize(v);"),h.push("}"))}h.push("out vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push(" mat[0][0] = 1.0;"),h.push(" mat[0][1] = 0.0;"),h.push(" mat[0][2] = 0.0;"),"spherical"===o&&(h.push(" mat[1][0] = 0.0;"),h.push(" mat[1][1] = 1.0;"),h.push(" mat[1][2] = 0.0;")),h.push(" mat[2][0] = 0.0;"),h.push(" mat[2][1] = 0.0;"),h.push(" mat[2][2] =1.0;"),h.push("}"));h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),n&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=i.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=s.sectionPlanes.length;e 0.0) { discard; }"),n.push("}")}"points"===i.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 s=e._state,i=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=s.billboard,l=s.background,h=s.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),A=ps(e),u=i.sectionPlanes.length>0,p=us(e),d=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),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(A){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("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&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(p){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=ps(e),h=i.uvBuf,c="PhongMaterial"===n.type,A="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,p=us(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));p&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+As[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("}")),(A||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 = "+As[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;"),i.colors&&f.push("in vec4 vColor;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");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;");h&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));h&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));h&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));h&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&h&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&h&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&h&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));h&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));h&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&h&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&h&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&h&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===i.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);");i.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;");i.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;");h&&(l&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));h&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+As[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));h&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+As[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));h&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+As[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));h&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+As[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));h&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));h&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){h&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),h&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),h&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),h&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),h&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),h&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),h&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),A&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||A)&&(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 s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,A=o.sectionPlanes.length;c0&&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&&i.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class ys{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,i=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.sectionPlanes.length>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;"),i){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.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);"),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;");i&&(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);"),i&&(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; "));i&&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;"),i)for(let e=0,t=s.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;"));i&&(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=s.sectionPlanes.length;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;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const gs=new t({}),vs=p.vec3(),Is=function(e,t){this.id=gs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ys(t),this._allocate(t)},_s={};Is.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=_s[t];return s||(s=new Is(t,e),_s[t]=s,d.memory.programs++),s._useCount++,s},Is.prototype.put=function(){0==--this._useCount&&(gs.removeItem(this.id),this._program&&this._program.destroy(),delete _s[this._hash],d.memory.programs--)},Is.prototype.webglContextRestored=function(){this._program=null},Is.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl,n=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._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),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&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;"));s&&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;"),i&&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;"),s&&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,s=e.scene._sectionPlanesState,i=e.scene.gammaOutput,r=s.sectionPlanes.length>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;"));i&&(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=s.sectionPlanes.length;e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");i?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Rs=new t({}),Ps=p.vec3(),Ds=function(e,t){this.id=Rs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ts(t),this._allocate(t)},bs={};Ds.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=bs[t];return s||(s=new Ds(t,e),bs[t]=s,d.memory.programs++),s._useCount++,s},Ds.prototype.put=function(){0==--this._useCount&&(Rs.removeItem(this.id),this._program&&this._program.destroy(),delete bs[this._hash],d.memory.programs--)},Ds.prototype.webglContextRestored=function(){this._program=null},Ds.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const i=this._scene,r=i.camera,o=i.canvas.gl;let n;const a=t._state,l=t._geometry,h=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const s=i._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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); "),i&&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;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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;"),i){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 Ns=p.vec3(),Os=function(e,t){this._hash=e,this._shaderSource=new Cs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ss={};Os.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Ss[t];if(!s){if(s=new Os(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ss[t]=s,d.memory.programs++}return s._useCount++,s},Os.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ss[this._hash],d.memory.programs--)},Os.prototype.webglContextRestored=function(){this._program=null},Os.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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)),i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t>24&255,c=l>>16&255,A=l>>8&255,u=255&l;i.uniform4f(this._uPickColor,u/255,A/255,c/255,h/255),i.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(i.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&i.drawArrays(i.TRIANGLES,0,n.positions.numItems)},Os.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ge(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0,i=!!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;"),s&&(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;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 ws=p.vec3(),Bs=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new xs(t),this._allocate(t)},Ms={};Bs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ms[t];if(!s){if(s=new Bs(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ms[t]=s,d.memory.programs++}return s._useCount++,s},Bs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ms[this._hash],d.memory.programs--)},Bs.prototype.webglContextRestored=function(){this._program=null},Bs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,h=o.backfaces,c=o.frontface,A=s.camera.project,u=n._getPickTrianglePositions(),p=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(A.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}if(i.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,i=!!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;"),i&&n.push("uniform mat4 positionsDecodeMatrix;");s&&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;"),i&&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; "));s&&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,s=t._sectionPlanesState,i=s.sectionPlanes.length>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(i){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 Ls=p.vec3(),Us=function(e,t){this._hash=e,this._shaderSource=new Fs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Hs={};Us.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Hs[t];if(!s){if(s=new Us(t,e),s.errors)return console.log(s.errors.join("\n")),null;Hs[t]=s,d.memory.programs++}return s._useCount++,s},Us.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Hs[this._hash],d.memory.programs--)},Us.prototype.webglContextRestored=function(){this._program=null},Us.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,i=s.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?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const s=r.frontface;e.frontface!==s&&(s?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=s),this._lastMaterialId=r.id}const l=s.camera;if(i.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,i=[];i.push("// Mesh shadow vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform vec3 offset;"),s&&i.push("uniform mat4 positionsDecodeMatrix;");t&&i.push("out vec4 vWorldPosition;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),i.push("vec4 worldPosition;"),s&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push("worldPosition = modelMatrix * localPosition;"),i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&i.push("vWorldPosition = worldPosition;");return i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,i=s.sectionPlanes.length>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),i){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 Vs=function(e,t){this._hash=e,this._shaderSource=new Gs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ks={};Vs.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=ks[s];if(!i){if(i=new Vs(s,e),i.errors)return console.log(i.errors.join("\n")),null;ks[s]=i,d.memory.programs++}return i._useCount++,i},Vs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ks[this._hash],d.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,i=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const r=i.frontface;e.frontface!==r&&(r?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=r),e.lineWidth!==i.lineWidth&&(s.lineWidth(i.lineWidth),e.lineWidth=i.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,i.pointSize),this._lastMaterialId=i.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),r.combineGeometry){const i=t.vertexBufs;i.id!==this._lastVertexBufsId&&(i.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=i.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(s.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(s.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(s.drawArrays(s.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Vs.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new ge(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uShadowViewMatrix=i.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=i.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let s=0;s0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ti=function(){const e=p.vec3(),t=p.vec3(),s=p.vec3(),i=p.vec3(),r=p.vec3(),o=p.vec3(),n=p.vec4(),a=p.vec3(),l=p.vec3(),h=p.vec3(),c=p.vec3(),A=p.vec3(),u=p.vec3(),d=p.vec3(),f=p.vec3(),m=p.vec3(),E=p.vec4(),y=p.vec4(),g=p.vec4(),v=p.vec3(),I=p.vec3(),_=p.vec3(),T=p.vec3(),R=p.vec3(),P=p.vec3(),D=p.vec3(),b=p.vec3(),C=p.vec3(),N=p.vec3(),O=p.vec3();return function(x,w,B,M){var F=M.primIndex;if(null!=F&&F>-1){const G=x.geometry._state,V=x.scene,k=V.camera,j=V.canvas;if("triangles"===G.primitiveName){M.primitive="triangle";const V=F,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var L=Q[V+0],U=Q[V+1],H=Q[V+2];o[0]=L,o[1]=U,o[2]=H,M.indices=o,z=3*L,K=3*U,Y=3*H}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],i[0]=W[K+0],i[1]=W[K+1],i[2]=W[K+2],r[0]=W[Y+0],r[1]=W[Y+1],r[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(gt.decompressPosition(s,e,s),gt.decompressPosition(i,e,i),gt.decompressPosition(r,e,r))}M.canvasPos?p.canvasPosToLocalRay(j.canvas,x.origin?S(w,x.origin):w,B,x.worldMatrix,M.canvasPos,e,t):M.origin&&M.direction&&p.worldRayToLocalRay(x.worldMatrix,M.origin,M.direction,e,t),p.normalizeVec3(t),p.rayPlaneIntersect(e,t,s,i,r,n),M.localPos=n,M.position=n,E[0]=n[0],E[1]=n[1],E[2]=n[2],E[3]=1,p.transformVec4(x.worldMatrix,E,y),a[0]=y[0],a[1]=y[1],a[2]=y[2],M.canvasPos&&x.origin&&(a[0]+=x.origin[0],a[1]+=x.origin[1],a[2]+=x.origin[2]),M.worldPos=a,p.transformVec4(k.matrix,y,g),l[0]=g[0],l[1]=g[1],l[2]=g[2],M.viewPos=l,p.cartesianToBarycentric(n,s,i,r,h),M.bary=h;const X=G.normals;if(X){if(G.compressGeometry){const e=3*L,t=3*U,s=3*H;gt.decompressNormal(X.subarray(e,e+2),c),gt.decompressNormal(X.subarray(t,t+2),A),gt.decompressNormal(X.subarray(s,s+2),u)}else c[0]=X[z],c[1]=X[z+1],c[2]=X[z+2],A[0]=X[K],A[1]=X[K+1],A[2]=X[K+2],u[0]=X[Y],u[1]=X[Y+1],u[2]=X[Y+2];const e=p.addVec3(p.addVec3(p.mulVec3Scalar(c,h[0],v),p.mulVec3Scalar(A,h[1],I),_),p.mulVec3Scalar(u,h[2],T),R);M.worldNormal=p.normalizeVec3(p.transformVec3(x.worldNormalMatrix,e,P))}const Z=G.uv;if(Z){if(d[0]=Z[2*L],d[1]=Z[2*L+1],f[0]=Z[2*U],f[1]=Z[2*U+1],m[0]=Z[2*H],m[1]=Z[2*H+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(gt.decompressUV(d,e,d),gt.decompressUV(f,e,f),gt.decompressUV(m,e,m))}M.uv=p.addVec3(p.addVec3(p.mulVec2Scalar(d,h[0],D),p.mulVec2Scalar(f,h[1],b),C),p.mulVec2Scalar(m,h[2],N),O)}}}}}();function si(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let i=e.height||1;i<0&&(console.error("negative height not allowed - will invert"),i*=-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,h=a?a[1]:0,c=a?a[2]:0,A=i/2,u=i/o,p=2*Math.PI/r,d=1/r,f=(t-s)/o,m=[],E=[],g=[],v=[];let I,_,T,R,P,D,b,C,N,O,S;const x=(90-180*Math.atan(i/(s-t))/Math.PI)/90;for(I=0;I<=o;I++)for(P=t-I*f,D=A-I*u,_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),E.push(P*T),E.push(x),E.push(P*R),g.push(_*d),g.push(1*I/o),m.push(P*T+l),m.push(D+h),m.push(P*R+c);for(I=0;I0){for(N=m.length/3,E.push(0),E.push(1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(t*T),E.push(1),E.push(t*R),g.push(O),g.push(S),m.push(t*T+l),m.push(A+h),m.push(t*R+c);for(_=0;_0){for(N=m.length/3,E.push(0),E.push(-1),E.push(0),g.push(.5),g.push(.5),m.push(0+l),m.push(0-A+h),m.push(0+c),_=0;_<=r;_++)T=Math.sin(_*p),R=Math.cos(_*p),O=.5*Math.sin(_*p)+.5,S=.5*Math.cos(_*p)+.5,E.push(s*T),E.push(-1),E.push(s*R),g.push(O),g.push(S),m.push(s*T+l),m.push(0-A+h),m.push(s*R+c);for(_=0;_0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,i=e.length;s1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=fi(s,this.wrapS);o&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,o);const n=fi(s,this.wrapT);if(n&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,n),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=fi(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}r?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,gi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,gi(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,fi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,fi(s,this.magFilter)));const a=fi(s,this.format,this.encoding),l=fi(s,this.type),h=yi(s,this.internalFormat,a,l,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,i,h,e[0].width,e[0].height);for(let t=0,i=e.length;t>t;return e+1}class Ti extends N{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Ge({texture:new Ei({gl:this.scene.canvas.gl}),matrix:p.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=p.vec2([0,0]),this._scale=p.vec2([1,1]),this._rotate=p.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return(e=e||Zt)!==Kt&&e!==Yt&&e!==Zt&&e!==zt&&e!==Wt&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=Zt),e}_checkMagFilter(e){return(e=e||Kt)!==Kt&&e!==Qt&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=Kt),e}_checkWrapS(e){return(e=e||Vt)!==kt&&e!==jt&&e!==Vt&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Vt),e}_checkWrapT(e){return(e=e||Vt)!==kt&&e!==jt&&e!==Vt&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=Vt),e}_checkFlipY(e){return!!e}_checkEncoding(e){return(e=e||ls)!==ls&&e!==hs&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=ls),e}_webglContextRestored(){this._state.texture=new Ei({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=p.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=p.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?p.mulMat4(t,s):s),0!==this._rotate&&(s=p.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?p.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=vi(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=vi(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}const Ri=d.memory,Pi=p.AABB3();class Di extends At{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Ge({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=p.OBB3();const s=this._state,i=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=i.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=i.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=i.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=i.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=i.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=i.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=i.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=i.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=gt.getPositionsBounds(t.positions),o=gt.compressPositions(t.positions,e.min,e.max);r=o.quantized,s.positionsDecodeMatrix=o.decodeMatrix,s.positionsBuf=new ve(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),Ri.positions+=s.positionsBuf.numItems,p.positions3ToAABB3(t.positions,this._aabb),p.positions3ToAABB3(r,Pi,s.positionsDecodeMatrix),p.AABB3ToOBB3(Pi,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new ve(i,i.ARRAY_BUFFER,e,e.length,4,i.STATIC_DRAW),Ri.colors+=s.colorsBuf.numItems}if(t.uv){const e=gt.getUVBounds(t.uv),r=gt.compressUVs(t.uv,e.min,e.max),o=r.quantized;s.uvDecodeMatrix=r.decodeMatrix,s.uvBuf=new ve(i,i.ARRAY_BUFFER,o,o.length,2,i.STATIC_DRAW),Ri.uvs+=s.uvBuf.numItems}if(t.normals){const e=gt.compressNormals(t.normals);let r=s.compressGeometry;s.normalsBuf=new ve(i,i.ARRAY_BUFFER,e,e.length,3,i.STATIC_DRAW,r),Ri.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,e,e.length,1,i.STATIC_DRAW),Ri.indices+=s.indicesBuf.numItems;const o=ut(r,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Ri.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(),Ri.meshes--}}var bi={};function Ci(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let i=e.xSegments||1;i<0&&(console.error("negative xSegments not allowed - will invert"),i*=-1),i<1&&(i=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,h=t/2,c=s/2,A=Math.floor(i)||1,u=Math.floor(r)||1,p=A+1,d=u+1,f=t/A,m=s/u,E=new Float32Array(p*d*3),g=new Float32Array(p*d*3),v=new Float32Array(p*d*2);let I,_,T,R,P,D,b,C=0,N=0;for(I=0;I65535?Uint32Array:Uint16Array)(A*u*6);for(I=0;I360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const h=n?n[2]:0,c=[],A=[],u=[],d=[];let f,m,E,g,v,I,_,T,R,P,D,b;for(T=0;T<=r;T++)for(_=0;_<=i;_++)f=_/i*o,m=.785398+T/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),E=(t+s*Math.cos(m))*Math.cos(f),g=(t+s*Math.cos(m))*Math.sin(f),v=s*Math.sin(m),c.push(E+a),c.push(g+l),c.push(v+h),u.push(1-_/i),u.push(T/r),I=p.normalizeVec3(p.subVec3([E,g,v],[a,l,h],[]),[]),A.push(I[0]),A.push(I[1]),A.push(I[2]);for(T=1;T<=r;T++)for(_=1;_<=i;_++)R=(i+1)*T+_-1,P=(i+1)*(T-1)+_-1,D=(i+1)*(T-1)+_,b=(i+1)*T+_,d.push(R),d.push(P),d.push(D),d.push(D),d.push(b),d.push(R);return y.apply(e,{positions:c,normals:A,uv:u,indices:d})}bi.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},bi.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(bi.parse._buffToStr(e));window.location.href=s},bi.clone=function(e){return JSON.parse(JSON.stringify(e))},bi.bin={},bi.bin.f=new Float32Array(1),bi.bin.fb=new Uint8Array(bi.bin.f.buffer),bi.bin.rf=function(e,t){for(var s=bi.bin.f,i=bi.bin.fb,r=0;r<4;r++)i[r]=e[t+r];return s[0]},bi.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},bi.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},bi.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},bi.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},bi.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},bi.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},bi.parse={},bi.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",i=0;ir&&(r=l),ho&&(o=h),cn&&(n=c)}return{min:{x:t,y:s,z:i},max:{x:r,y:o,z:n}}};class Oi extends N{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=p.vec3(t.pos||[0,0,0]),this._up=p.vec3(t.up||[0,1,0]),this._normal=p.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=p.vec3(),this._rtcPos=p.vec3(),this._imageSize=p.vec2(),this._texture=new Ti(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 di(this,{matrix:p.inverseMat4(p.lookAtMat4v(this._pos,p.subVec3(this._pos,this._normal,p.mat4()),this._up,p.mat4())),children:[this._bitmapMesh=new ei(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new _t(this,Ci({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new bt(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 Si=p.vec3(),xi=p.vec3(),wi=p.mat4();class Bi{constructor(){this.normal=p.vec3(),this.offset=0,this.testVertex=p.vec3()}set(e,t,s,i){const r=1/Math.sqrt(e*e+t*t+s*s);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=s*r,this.offset=i*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class Mi{constructor(){this.planes=[new Bi,new Bi,new Bi,new Bi,new Bi,new Bi]}}function Fi(e,t){let s=Mi.INSIDE;const i=Si,r=xi;i[0]=t[0],i[1]=t[1],i[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[i,r];for(let t=0;t<6;++t){const i=e.planes[t];if(i.normal[0]*o[i.testVertex[0]][0]+i.normal[1]*o[i.testVertex[1]][1]+i.normal[2]*o[i.testVertex[2]][2]+i.offset<0)return Mi.OUTSIDE;i.normal[0]*o[1-i.testVertex[0]][0]+i.normal[1]*o[1-i.testVertex[1]][1]+i.normal[2]*o[1-i.testVertex[2]][2]+i.offset<0&&(s=Mi.INTERSECT)}return s}Mi.INSIDE=0,Mi.INTERSECT=1,Mi.OUTSIDE=2;class Li extends N{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),i=p.vec3(),r=w(this._positions,new Float32Array(this._positions.length),i,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ed.has(e.id)||m.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let i,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}(s.colorize);s.xrayed?(i=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,i=Math.round(255*i).toString(16).padStart(2,"0"),r=i+r):d.has(s.id)&&(i=Math.round(255*s.opacity).toString(16).padStart(2,"0"),r=i+r),e[r]||(e[r]=[]);const o=s.id,n=s.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),y=Object.entries(E).map((([e,t])=>({color:e,components:t})));o.components.coloring=y;const g=t.objectIds,v=t.visibleObjects,I=t.visibleObjectIds,_=g.filter((e=>!v[e])),T=t.selectedObjectIds;return e.defaultInvisible||I.length<_.length?(o.components.visibility.exceptions=this._createBCFComponents(I),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(_),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(T),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let i=0,r=e.length;i0&&e.clipping_planes.forEach((function(e){let t=Qi(e.location,Ui),s=Qi(e.direction,Ui);h&&p.negateVec3(s),p.subVec3(t,l),r.yUp&&(t=zi(t),s=zi(s)),new ri(i,{pos:t,dir:s})})),i.clearLines(),e.lines&&e.lines.length>0){const t=[],s=[];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),s.push(r++),s.push(r++))})),new Li(i,{positions:t,indices:s,clippable:!1,collidable:!0})}if(i.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let o=Qi(e.location,Hi),n=Qi(e.normal,Gi),a=Qi(e.up,Vi),l=e.height||1;t&&s&&o&&n&&a&&(r.yUp&&(o=zi(o),n=zi(n),a=zi(a)),new Oi(i,{src:s,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsHighlighted(i.highlightedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(i.setObjectsVisible(i.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(i.setObjectsVisible(i.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&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===r.openings_visible&&i.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!1),r.space_boundaries_visible)}e.components.selection&&(i.setObjectsSelected(i.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,i=0,r=!1;8===s.length&&(i=parseInt(s.substring(0,2),16)/256,i<=1&&i>=.95&&(i=1),s=s.substring(2),r=!0);const 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((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=i)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,h,c,A;if(e.perspective_camera?(a=Qi(e.perspective_camera.camera_view_point,Ui),h=Qi(e.perspective_camera.camera_direction,Ui),c=Qi(e.perspective_camera.camera_up_vector,Ui),r.perspective.fov=e.perspective_camera.field_of_view,A="perspective"):(a=Qi(e.orthogonal_camera.camera_view_point,Ui),h=Qi(e.orthogonal_camera.camera_direction,Ui),c=Qi(e.orthogonal_camera.camera_up_vector,Ui),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,A="ortho"),p.subVec3(a,l),r.yUp&&(a=zi(a),h=zi(h),c=zi(c)),o){const e=i.pick({pickSurface:!0,origin:a,direction:h});h=e?e.worldPos:p.addVec3(a,h,Ui)}else h=p.addVec3(a,h,Ui);n?(r.eye=a,r.look=h,r.up=c,r.projection=A):s.cameraFlight.flyTo({eye:a,look:h,up:c,duration:t.duration,projection:A})}}_withBCFComponent(e,t,s){const i=this.viewer,r=i.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 s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void s(n);if(e.updateCompositeObjects){if(i.metaScene.metaObjects[o])return void r.withObjects(i.metaScene.getObjectIDsInSubtree(o),s)}Object.keys(r.models).forEach((t=>{const n=p.globalizeObjectId(t,o),a=r.objects[n];if(a)s(a);else if(e.updateCompositeObjects){i.metaScene.metaObjects[n]&&r.withObjects(i.metaScene.getObjectIDsInSubtree(n),s)}}))}}destroy(){super.destroy()}}function ji(e){return{x:e[0],y:e[1],z:e[2]}}function Qi(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Wi(e){return new Float64Array([e[0],-e[2],e[1]])}function zi(e){return new Float64Array([e[0],e[2],-e[1]])}const Ki=p.vec3(),Yi=(e,t,s,i)=>{var r=e-s,o=t-i;return Math.sqrt(r*r+o*o)};class Xi extends N{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new Z(s,t.origin),this._targetMarker=new Z(s,t.target),this._originWorld=p.vec3(),this._targetWorld=p.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 i=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._targetDot=new J(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthWire=new q(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisWire=new q(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisWire=new q(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisWire=new q(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._lengthLabel=new $(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._xAxisLabel=new $(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._yAxisLabel=new $(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._zAxisLabel=new $(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:i,onMouseLeave:r,onMouseWheel:n,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;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&&(p.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);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var i=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,h=l[2],c=l[3],A=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,m=s.units,E=s.unitsInfo[m].abbrev;for(var u=0,d=i.length;u{r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=e.canvasPos[0]-5+"px",this._markerDiv.style.marginTop=e.canvasPos[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red")):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),i.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.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),i.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),i.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.centerPos=e.cursorPos||e.canvasPos,this.pointerLens.cursorPos=e.canvasPos),r=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),i.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null)}destroy(){this.deactivate(),super.destroy()}}class Ji extends a{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._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 qi(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,s=e.target,i=new Xi(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:s.entity,worldPos:s.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,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[i.id]=i,i.on("destroyed",(()=>{delete this._measurements[i.id]})),this.fire("measurementCreated",i),i}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,s]of Object.entries(this.measurements))s.labelShown=e}setAxisVisible(e){for(const[t,s]of Object.entries(this.measurements))s.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,s=e.length;t{s=1e3*this._delayBeforeRestoreSeconds,i||(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,i=!0)};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(t=>{i&&(s-=t.deltaTime,(!this._delayBeforeRestore||s<=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),i=!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 er{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const i=tr(e,s);return i?t?sr(i,t):i:null}translatePlurals(e,t,s){const i=this._messages[this._locale];if(!i)return null;let r=tr(e,i);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=sr(r,[t]),s&&(r=sr(r,s)),r):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const i=this._eventSubs[e];if(i)for(const e in i)if(i.hasOwnProperty(e)){i[e].callback(t)}}on(e,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new t),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);const r=this._eventSubIDMap.addItem();i[r]={callback:s},this._eventSubEvents[r]=e;const o=this._events[e];return void 0!==o&&s(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function tr(e,t){if(t[e])return t[e];const s=e.split(".");let i=t;for(let e=0,t=s.length;i&&e=1;e>1&&(e=1);const s=this.easing?lr._ease(e,0,1,1):e,i=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(p.subVec3(i.eye,i.look,ar),i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,or),i.look=p.subVec3(or,ar,rr)):this._flyingLook&&(i.look=p.lerpVec3(s,0,1,this._look1,this._look2,rr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,nr)):this._flyingEyeLookUp&&(i.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,or),i.look=p.lerpVec3(s,0,1,this._look1,this._look2,rr),i.up=p.lerpVec3(s,0,1,this._up1,this._up2,nr)),this._projection2){const t="ortho"===this._projection2?lr._easeOutExpo(e,0,1,1):lr._easeInCubic(e,0,1,1);i.customProjection.matrix=p.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else i.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return i.ortho.scale=this._orthoScale2,void this.stop();b.scheduleTask(this._update,this)}static _ease(e,t,s,i){return-s*(e/=i)*(e-2)+t}static _easeInCubic(e,t,s,i){return s*(e/=i)*e*e+t}static _easeOutExpo(e,t,s,i){return s*(1-Math.pow(2,-10*e/i))+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 hr extends N{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new lr(this),this._t=0,this.state=hr.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const i=performance.now(),r=this._lastTime?.001*(i-this._lastTime):0;if(this._lastTime=i,0!==r)switch(this.state){case hr.SCRUBBING:return;case hr.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=hr.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case hr.PLAYING_TO:s=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=hr.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,i){return-s*(e/=i)*(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=hr.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=hr.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const i=s.frames[e];i?(this.state=hr.SCRUBBING,this._cameraFlightAnimation.flyTo(i,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=hr.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=hr.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=hr.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}hr.STOPPED=0,hr.SCRUBBING=1,hr.PLAYING=2,hr.PLAYING_TO=3,p.vec3(),p.vec3(),p.vec3(),p.vec3([0,-1,0]),p.vec4([0,0,0,1]);const cr=p.vec3();class Ar{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,s){this.numObjects=0,this._mask=s?y.apply(s,{}):null;const i=!s||s.visible,r=!s||s.edges,o=!s||s.xrayed,n=!s||s.highlighted,a=!s||s.selected,l=!s||s.clippable,h=!s||s.pickable,c=!s||s.colorize,A=!s||s.opacity,u=t.metaObjects,p=e.objects;for(let e=0,t=u.length;e0){const n=t._sectionPlanesState.sectionPlanes,a=r*o,l=i.renderFlags;for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const s=a.drawingBufferWidth,i=a.drawingBufferHeight;yr[0]=s,yr[1]=i,yr[2]=t.blendCutoff,yr[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,yr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(i){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===fr[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=n.xrayMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===fr[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=n.highlightMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else if(s===fr[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=n.selectedMaterial._state,i=s[e],r=s[t];a.uniform4f(this._uColor,i[0],i[1],i[2],r)}else a.uniform4fv(this._uColor,this._edges?Er:mr)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class Tr extends _r{constructor(e,t,{instancing:s=!1,edges:i=!1}={}){super(e,t,{instancing:s,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=i.pickElementsCount||s.indicesBuf.numItems,o=i.pickElementsOffset?i.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,o),r&&i.drawElements++}}}class Rr extends Tr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Pr extends _r{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++)}}class Dr extends Pr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class br extends _r{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),r&&i.drawArrays++}}class Cr extends _r{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),r&&i.drawArrays++}}class Nr extends _r{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),r&&i.drawElements++}}class Or extends _r{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:i,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),r&&i.drawElements++}}class Sr extends Tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;e0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class xr extends Tr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,i=s.sectionPlanes.length>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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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,s=t.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 Br extends Rr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class Mr extends Rr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class Fr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class Lr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Ur extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Hr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Gr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching depth fragment shader"),i.push("precision highp float;"),i.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}}class Vr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class kr extends Tr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class jr extends Tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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;")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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;"),i.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching pick flat normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Wr extends Tr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,i=e._sectionPlanesState,r=i.sectionPlanes.length>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=i.sectionPlanes.length;e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;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=s.lights.length;e5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Xr=p.mat4(),Zr=p.mat4();function qr(e,t,s){const i=e.length,r=new Uint16Array(i),o=t[0],n=t[1],a=t[2],l=t[3]-o,h=t[4]-n,c=t[5]-a,A=65525,u=A/l,d=A/h,f=A/c,m=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(i))*(r>=0?1:-1),i=e,r=t}return new Int8Array([Math[t](127.5*i+(i<0?-1:0)),Math[s](127.5*r+(r<0?-1:0))])}function eo(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const i=1-Math.abs(t)-Math.abs(s);i<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const r=Math.sqrt(t*t+s*s+i*i);return[t/r,s/r,i/r]}const to=p.vec3(),so=p.vec3(),io=p.vec3(),ro=p.vec3(),oo=p.mat4();class no extends _r{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=to;let m,E;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=so;if(l){const e=io;p.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=S(d,t,oo),E=ro,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ao=p.vec3(),lo=p.vec3(),ho=p.vec3(),co=p.vec3(),Ao=p.mat4();class uo extends _r{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ao;let m,E;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=lo;if(l){const e=ho;p.transformPoint3(c,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=S(d,t,Ao),E=co,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class po{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new no(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new uo(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new no(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new uo(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const fo={};const mo=p.mat4(),Eo=p.mat4(),yo=p.vec4([0,0,0,1]),go=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.OBB3();const vo=p.vec3(),Io=p.vec3(),_o=p.vec3(),To=p.vec3(),Ro=p.vec3(),Po=p.vec3(),Do=p.vec3();class bo{constructor(e){console.info("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Kr[t];return s||(s=new zr(e),Kr[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Kr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=fo[t];return s||(s=new po(e),fo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete fo[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Yr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ge({origin:p.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=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=p.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=p.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=p.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)for(let e=0,t=r.length;e0){const e=mo;m?p.inverseMat4(p.transposeMat4(m,Eo),e):p.identityMat4(e,e),function(e,t,s,i,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,h,c,A,u=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(A=0;Ac&&(l=n,c=h),n=$r(d,"floor","ceil"),a=eo(n),h=o(d,a),h>c&&(l=n,c=h),n=$r(d,"ceil","ceil"),a=eo(n),h=o(d,a),h>c&&(l=n,c=h),i[r+A+0]=l[0],i[r+A+1]=l[1],i[r+A+2]=0}(e,i,i.length,v.normals,v.normals.length)}if(a)for(let e=0,t=a.length;e0)for(let e=0,t=o.length;e0)for(let e=0,t=n.length;e0){const i=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):qr(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=p.mat4());if(e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,i.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const i=new Int8Array(s.normals);let r=!0;e.normalsBuf=new ve(t,t.ARRAY_BUFFER,i,s.normals.length,3,t.STATIC_DRAW,r)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.uv.length>0)if(e.uvDecodeMatrix){let i=!1;e.uvBuf=new ve(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,i)}else{const i=gt.getUVBounds(s.uv),r=gt.compressUVs(s.uv,i.min,i.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=p.mat3(r.decodeMatrix),e.uvBuf=new ve(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(s.metallicRoughness.length>0){const i=new Uint8Array(s.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new ve(t,t.ARRAY_BUFFER,i,s.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i),o=!1;e.flagsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ve(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const i=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,i,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,i=this._portions[s],r=4*i.vertsBaseIndex,o=4*i.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],h=t[2],c=t[3];for(let e=0;ey)&&(y=e,i.set(g),r&&p.triangleNormal(d,f,m,r),E=!0)}}return E&&r&&(p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),E}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 Co extends Pr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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=s.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("}"),i&&(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=s.lights.length;r0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}}class No extends Pr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let i,r;const o=t.sectionPlanes.length>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,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;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 ) );"),i=0,r=s.lights.length;i0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing fill fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class So extends Dr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class xo extends Dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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}}class wo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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 = vPickColor; "),i.push("}"),i}}class Bo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 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(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class Mo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 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(` outNormal = ivec4(vWorldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class Fo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Lo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 Uo extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class Ho extends Pr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}const Go={3e3:"linearToLinear",3001:"sRGBToLinear"};class Vo extends Pr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,i=t.sectionPlanes.length>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;"),s.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),i&&(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));")),i&&(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;"),s.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,s=e._sectionPlanesState,i=e._lightsState,r=s.sectionPlanes.length>0,o=s.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("}")),i.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),i.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.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("}"),i.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 = "+Go[i.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("}"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),i.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Go[i.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;")),i.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=s.sectionPlanes.length;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);"),i.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(i.lightMaps.length>0||i.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=i.lights.length;e0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),s){i.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${p.MAX_INT}), 1.0);`),i.push("}"),i}}class jo extends Pr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,i=e._lightsState;let r,o;const n=s.sectionPlanes.length>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=s.sectionPlanes.length;e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;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=i.lights.length;r0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Jo=p.vec3(),$o=p.vec3(),en=p.vec3(),tn=p.vec3(),sn=p.mat4();class rn extends _r{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Jo;let m,E;if(f[0]=p.safeInv(u[3]-u[0])*p.MAX_INT,f[1]=p.safeInv(u[4]-u[1])*p.MAX_INT,f[2]=p.safeInv(u[5]-u[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(f[0]),e.snapPickCoordinateScale[1]=p.safeInv(f[1]),e.snapPickCoordinateScale[2]=p.safeInv(f[2]),l||0!==h[0]||0!==h[1]||0!==h[2]){const t=$o;if(l){const e=p.transformPoint3(c,l,en);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=S(d,t,sn),E=tn,E[0]=o.eye[0]-t[0],E[1]=o.eye[1]-t[1],E[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=d,E=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,E),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,s),n.uniform1i(this._uPickInvisible,e.pickInvisible);let y=0;this._matricesUniformBlockBufferData.set(A,0),this._matricesUniformBlockBufferData.set(m,y+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,y+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,y+=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.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class on{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new qo(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new rn(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new qo(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new rn(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const nn={};const an=new Uint8Array(4),ln=new Float32Array(1),hn=p.vec4([0,0,0,1]),cn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]);const An=new Float32Array(3),un=p.vec3(),pn=p.vec3(),dn=p.vec3(),fn=p.vec3(),mn=p.vec3(),En=p.vec3(),yn=p.vec3();class gn{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=Wo[t];return s||(s=new Qo(e),Wo[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Wo[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=nn[t];return s||(s=new on(e),nn[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete nn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ge({numInstances:0,obb:p.OBB3(),origin:p.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf: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._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=p.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,i=e.roughness,r=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,o=e.meshMatrix,n=e.aabb,a=e.pickColor;if(this._finalized)throw"Already finalized";const l=t[0],h=t[1],c=t[2];if(this._colors.push(l),this._colors.push(h),this._colors.push(c),this._colors.push(r),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=i?i:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(o[0]),this._modelMatrixCol0.push(o[4]),this._modelMatrixCol0.push(o[8]),this._modelMatrixCol0.push(o[12]),this._modelMatrixCol1.push(o[1]),this._modelMatrixCol1.push(o[5]),this._modelMatrixCol1.push(o[9]),this._modelMatrixCol1.push(o[13]),this._modelMatrixCol2.push(o[2]),this._modelMatrixCol2.push(o[6]),this._modelMatrixCol2.push(o[10]),this._modelMatrixCol2.push(o[14]),this._state.geometry.normals){let e=p.transposeMat4(o,p.mat4()),t=p.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]);const A=this._state.geometry.positionsCompressed.length,u=this._state.geometry.positionsCompressed,d=this._state.geometry.positionsDecodeMatrix;for(let e=0;e0){let t=!1;e.colorsBuf=new ve(i,i.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,i.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new ve(i,i.ARRAY_BUFFER,t,this._metallicRoughness.length,2,i.STATIC_DRAW,s)}if(o>0){let t=!1;e.flagsBuf=new ve(i,i.ARRAY_BUFFER,new Float32Array(o),o,1,i.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,i.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new ve(i,i.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,i.STATIC_DRAW,s),e.positionsDecodeMatrix=p.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new ve(i,i.ARRAY_BUFFER,s,s.length,4,i.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new ve(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,i.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new ve(i,i.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,i.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelMatrixCol1Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelMatrixCol2Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,i.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new ve(i,i.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,i.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new ve(i,i.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,i.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";an[0]=t[0],an[1]=t[1],an[2]=t[2],an[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(an,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&M),r=!!(t&G),o=!!(t&V),n=!!(t&k),a=!!(t&j),l=!!(t&L),h=!!(t&F);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?fr.NOT_RENDERED:s?fr.COLOR_TRANSPARENT:fr.COLOR_OPAQUE,A=!i||h?fr.NOT_RENDERED:n?fr.SILHOUETTE_SELECTED:o?fr.SILHOUETTE_HIGHLIGHTED:r?fr.SILHOUETTE_XRAYED:fr.NOT_RENDERED;let u=0;u=!i||h?fr.NOT_RENDERED:n?fr.EDGES_SELECTED:o?fr.EDGES_HIGHLIGHTED:r?fr.EDGES_XRAYED:a?s?fr.EDGES_COLOR_TRANSPARENT:fr.EDGES_COLOR_OPAQUE:fr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?fr.PICK:fr.NOT_RENDERED)<<12,p|=(t&U?1:0)<<16,ln[0]=p,this._state.flagsBuf&&this._state.flagsBuf.setData(ln,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(An[0]=t[0],An[1]=t[1],An[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(An,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,i=s.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=i.quantizedPositions,n=s.origin,a=r.offset,l=n[0]+a[0],h=n[1]+a[1],c=n[2]+a[2],A=hn,u=r.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=o.length;eg)&&(g=e,i.set(v),r&&p.triangleNormal(f,m,E,r),y=!0)}}return y&&r&&(p.transformVec3(a.normalMatrix,r,r),p.transformVec3(this.model.worldNormalMatrix,r,r),p.normalizeVec3(r)),y}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 vn extends Nr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class In extends Nr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines batching silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class _n{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new vn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new In(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Tn={};class Rn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const Pn=p.vec4([0,0,0,1]),Dn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.OBB3();class bn{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Tn[t];return s||(s=new _n(e),Tn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Tn[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new Rn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ge({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=qr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.DYNAMIC_DRAW,r)}if(s.colors.length>0){const i=s.colors.length/4,r=new Float32Array(i);let o=!1;e.flagsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ve(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const i=new Uint32Array(s.indices);e.indicesBuf=new ve(t,t.ELEMENT_ARRAY_BUFFER,i,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],h=t[3];for(let e=0;e0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),s=0,i=t.sectionPlanes.length;s 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 Or{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Lines instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = color;"),i.push("}"),i}}class On{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Cn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Nn(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Sn={};const xn=new Uint8Array(4),wn=new Float32Array(1),Bn=p.vec4([0,0,0,1]),Mn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]);const Fn=new Float32Array(3);class Ln{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=Sn[t];return s||(s=new On(e),Sn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Sn[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ge({obb:p.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=p.vec3(e.origin)),this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,i=e.meshMatrix,r=e.aabb;if(this._finalized)throw"Already finalized";const o=t[0],n=t[1],a=t[2];t[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),p.collapseAABB3(r);const l=this._state.obb,h=l.length;for(let e=0;e0){let t=!1;this._state.colorsBuf=new ve(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";xn[0]=t[0],xn[1]=t[1],xn[2]=t[2],xn[3]=t[3],this._state.colorsBuf.setData(xn,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&M),r=!!(t&G),o=!!(t&V),n=!!(t&k),a=!!(t&j),l=!!(t&L),h=!!(t&F);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?fr.NOT_RENDERED:s?fr.COLOR_TRANSPARENT:fr.COLOR_OPAQUE,A=!i||h?fr.NOT_RENDERED:n?fr.SILHOUETTE_SELECTED:o?fr.SILHOUETTE_HIGHLIGHTED:r?fr.SILHOUETTE_XRAYED:fr.NOT_RENDERED;let u=0;u=!i||h?fr.NOT_RENDERED:n?fr.EDGES_SELECTED:o?fr.EDGES_HIGHLIGHTED:r?fr.EDGES_XRAYED:a?s?fr.EDGES_COLOR_TRANSPARENT:fr.EDGES_COLOR_OPAQUE:fr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?fr.PICK:fr.NOT_RENDERED)<<12,p|=(t&U?255:0)<<16,wn[0]=p,this._state.flagsBuf.setData(wn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Fn[0]=t[0],Fn[1]=t[1],Fn[2]=t[2],this._state.offsetsBuf.setData(Fn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Un extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Hn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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;"),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 Gn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching pick mesh 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batching pick mesh vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vPickColor; "),i.push("}"),i}}class Vn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batched 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),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("gl_PointSize += 10.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points batched 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("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class kn extends br{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points batching occlusion 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class jn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Un(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Hn(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Gn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new kn(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Qn={};class Wn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const zn=p.vec4(),Kn=p.vec4(),Yn=p.vec4([0,0,0,1]),Xn=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]),p.OBB3();class Zn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=Qn[t];return s||(s=new jn(e),Qn[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Qn[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Wn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Ge({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:p.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=p.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,i=e.color,r=e.colorsCompressed,o=e.colors,n=e.meshMatrix,a=e.worldAABB,l=e.pickColor,h=this._buffer,c=h.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e0)if(this._preCompressedPositionsExpected){const i=new Uint16Array(s.positions);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}else{const i=qr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ve(t,t.ARRAY_BUFFER,i,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const i=new Uint8Array(s.colors);let r=!1;e.colorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.colors.length,4,t.STATIC_DRAW,r)}if(s.positions.length>0){const i=s.positions.length/3,r=new Float32Array(i);let o=!1;e.flagsBuf=new ve(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(s.pickColors.length>0){const i=new Uint8Array(s.pickColors);let r=!1;e.pickColorsBuf=new ve(t,t.ARRAY_BUFFER,i,s.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const i=new Float32Array(s.offsets);e.offsetsBuf=new ve(t,t.ARRAY_BUFFER,i,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,i=4*this._portions[s],r=4*this._portions[s+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),s.filterIntensity&&i.push("uniform vec2 intensityRange;"),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 {"),s.filterIntensity&&(i.push("float intensity = float(color.a) / 255.0;"),i.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),s.filterIntensity&&i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing color fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Jn extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points 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 float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),i.push("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing silhouette fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vColor;"),i.push("}"),i}}class $n extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing pick mesh 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),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick mesh fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outColor = vPickColor; "),i.push("}"),i}}class ea extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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;"),i.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outColor = packDepth(zNormalizedDepth); "),i.push("}"),i}}class ta extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing occlusion vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0;e 1.0) {"),i.push(" discard;"),i.push(" }")),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class sa extends Cr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,i=[];return i.push("#version 300 es"),i.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),s.perspectivePoints&&i.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),s.perspectivePoints?(i.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),i.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),i.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):i.push("gl_PointSize = pointSize;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,i;const r=t.sectionPlanes.length>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;"),s=0,i=t.sectionPlanes.length;s 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;"),s=0,i=t.sectionPlanes.length;s 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 ia extends Cr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Instancing geometry depth drawing fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e 1.0) {"),i.push(" discard;"),i.push(" }"),s){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}}class ra{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new qn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new sa(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new $n(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ea(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ta(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ia(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const oa={};const na=new Uint8Array(4),aa=new Float32Array(1),la=p.vec4([0,0,0,1]),ha=p.vec4([0,0,0,1]);p.vec4([0,0,0,1]);const ca=new Float32Array(3);class Aa{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=oa[t];return s||(s=new ra(e),oa[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete oa[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new Ge({obb:p.OBB3(),numInstances:0,origin:e.origin?p.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),p.collapseAABB3(s);const r=this._state.obb,o=r.length;for(let e=0;e0){let i=!1;s.flagsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.positionsCompressed&&i.positionsCompressed.length>0){const t=!1;s.positionsBuf=new ve(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=p.mat4(i.positionsDecodeMatrix)}if(i.colorsCompressed&&i.colorsCompressed.length>0){const t=new Uint8Array(i.colorsCompressed),r=!1;s.colorsBuf=new ve(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new ve(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;s.pickColorsBuf=new ve(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";na[0]=t[0],na[1]=t[1],na[2]=t[2],this._state.colorsBuf.setData(na,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const i=!!(t&M),r=!!(t&G),o=!!(t&V),n=!!(t&k),a=!!(t&j),l=!!(t&L),h=!!(t&F);let c,A;c=!i||h||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?fr.NOT_RENDERED:s?fr.COLOR_TRANSPARENT:fr.COLOR_OPAQUE,A=!i||h?fr.NOT_RENDERED:n?fr.SILHOUETTE_SELECTED:o?fr.SILHOUETTE_HIGHLIGHTED:r?fr.SILHOUETTE_XRAYED:fr.NOT_RENDERED;let u=0;u=!i||h?fr.NOT_RENDERED:n?fr.EDGES_SELECTED:o?fr.EDGES_HIGHLIGHTED:r?fr.EDGES_XRAYED:a?s?fr.EDGES_COLOR_TRANSPARENT:fr.EDGES_COLOR_OPAQUE:fr.NOT_RENDERED;let p=0;p|=c,p|=A<<4,p|=u<<8,p|=(i&&!h&&l?fr.PICK:fr.NOT_RENDERED)<<12,p|=(t&U?255:0)<<16,aa[0]=p,this._state.flagsBuf.setData(aa,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ca[0]=t[0],ca[1]=t[1],ca[2]=t[2],this._state.offsetsBuf.setData(ca,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,fr.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,fr.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,fr.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class ua{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 pa{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const da={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={}}};const fa=new class{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==ma[e])return void ma[e].push({onLoad:t,onProgress:s,onError:i});ma[e]=[],ma[e].push({onLoad:t,onProgress:s,onError:i});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 s=ma[e],i=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(){i.read().then((({done:i,value:r})=>{if(i)e.close();else{a+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=s.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),s=t&&t[1]?t[1].toLowerCase():void 0,i=new TextDecoder(s);return e.arrayBuffer().then((e=>i.decode(e)))}}})).then((t=>{da.add(e,t);const s=ma[e];delete ma[e];for(let e=0,i=s.length;e{const s=ma[e];if(void 0===s)throw this.manager.itemError(e),t;delete ma[e];for(let e=0,i=s.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 ya{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 i=this._getIdleWorker();-1!==i?(this._initWorker(i),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let ga=0;class va{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new ya,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const i=e.capabilities;this._workerConfig={astcSupported:i.astcSupported,etc1Supported:i.etc1Supported,etc2Supported:i.etc2Supported,dxtSupported:i.dxtSupported,bptcSupported:i.bptcSupported,pvrtcSupported:i.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Ea;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new Ea;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const i=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,i]).then((([e,t])=>{const s=va.BasisWorker.toString(),i=["/* constants */","let _EngineFormat = "+JSON.stringify(va.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(va.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(va.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([i])),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}))})),ga>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),ga++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((i,r)=>{const o=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const s=e.data,{mipmaps:o,width:n,height:a,format:l,type:h,error:c,dfdTransferFn:A,dfdFlags:u}=s;if("error"===h)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?Kt:Xt,magFilter:1===o.length?Kt:Xt,encoding:2===A?hs:ls,premultiplyAlpha:!!(1&u)}}),i()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),ga--}}va.BasisFormat={ETC1S:0,UASTC_4x4:1},va.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},va.EngineFormat={RGBAFormat:qt,RGBA_ASTC_4x4_Format:ns,RGBA_BPTC_Format:as,RGBA_ETC2_EAC_Format:os,RGBA_PVRTC_4BPPV1_Format:is,RGBA_S3TC_DXT5_Format:ts,RGB_ETC1_Format:36196,RGB_ETC2_Format:rs,RGB_PVRTC_4BPPV1_Format:ss,RGB_S3TC_DXT1_Format:Jt},va.BasisWorker=function(){let e,t,s;const i=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((e=>{s={wasmBinary:A,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:A,mipmaps:u,format:p,dfdTransferFn:d,dfdFlags:f}=function(t){const n=new s.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const A=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),p=n.getHeight(),d=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),E=n.getDFDFlags(),{transcoderFormat:y,engineFormat:g}=function(t,s,n,c){let A,u;const p=t===o.ETC1S?a:l;for(let i=0;i>t;s.sort(ba);const i=new Int32Array(e.length);for(let t=0,r=s.length;te[t+1]){let s=e[t];e[t]=e[t+1],e[t+1]=s}Ca=new Int32Array(e),t.sort(Na);const s=new Int32Array(e.length);for(let i=0,r=t.length;it){let s=e;e=t,t=s}function s(s,i){return s!==e?e-s:i!==t?t-i:0}let i=0,r=(o.length>>1)-1;for(;i<=r;){const e=r+i>>1,t=s(o[2*e],o[2*e+1]);if(t>0)i=e+1;else{if(!(t<0))return e;r=e-1}}return-i-1}const a=new Int32Array(o.length/2);a.fill(0);const l=i.length/3;if(l>8*(1<u.maxNumPositions&&(u=A()),u.bucketNumber>8)return[e];let d;-1===h[l]&&(h[l]=u.numPositions++,u.positionsCompressed.push(i[3*l]),u.positionsCompressed.push(i[3*l+1]),u.positionsCompressed.push(i[3*l+2])),-1===h[c]&&(h[c]=u.numPositions++,u.positionsCompressed.push(i[3*c]),u.positionsCompressed.push(i[3*c+1]),u.positionsCompressed.push(i[3*c+2])),-1===h[p]&&(h[p]=u.numPositions++,u.positionsCompressed.push(i[3*p]),u.positionsCompressed.push(i[3*p+1]),u.positionsCompressed.push(i[3*p+2])),u.indices.push(h[l]),u.indices.push(h[c]),u.indices.push(h[p]),(d=n(l,c))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(l,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(c,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]]))}const p=t/8*2,d=t/8,f=2*i.length+(r.length+o.length)*p;let m=0,E=-i.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*d,E+=e.positionsCompressed.length/3})),m>f?[e]:(s&&function(e,t){const s={};let i=0;e.forEach((e=>{const t=e.indices,r=e.edgeIndices,o=e.positionsCompressed;for(let e=0,i=t.length;e0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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,s=e._lightsState;if(this._program=new ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=s.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 sceneModelWorldMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),o.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),o.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform highp sampler2D uTextureModelMatrices;"),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=s.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, 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 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, 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*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),o.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),o.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),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=s.lights.length;e0,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"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ua=new Float32Array([1,1,1]),Ha=p.vec3(),Ga=p.vec3(),Va=p.vec3(),ka=p.vec3(),ja=p.mat4();class Qa{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=Ha;if(h){const t=Ga;p.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,ja),m=Va,m[0]=r.eye[0]-e[0],m[1]=r.eye[1]-e[1],m[2]=r.eye[2]-e[2]}else f=d,m=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),s===fr.SILHOUETTE_XRAYED){const e=i.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.SILHOUETTE_HIGHLIGHTED){const e=i.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.SILHOUETTE_SELECTED){const e=i.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,Ua);if(i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const E=i._sectionPlanesState.sectionPlanes.length;if(E>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.y) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 Wa=new Float32Array([0,0,0,1]),za=p.vec3(),Ka=p.vec3(),Ya=p.vec3(),Xa=p.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,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=za;if(m){const t=p.transformPoint3(A,h,Ka);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,Xa)}else f=d;if(n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),s===fr.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,Wa);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 qa=p.vec3(),Ja=p.vec3(),$a=p.vec3(),el=p.mat4();class tl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=qa;if(m){const t=p.transformPoint3(A,h,Ja);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,el)}else f=d;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureEdgesColorRenderer"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled,s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push(" vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vec4 rgb = vec4(color.rgba);"),s.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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=p.vec3(),il=p.vec3(),rl=p.vec3(),ol=p.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,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i;let d,f;l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=sl;if(m){const t=p.transformPoint3(A,h,il);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=S(o.viewMatrix,e,ol),f=rl,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("smooth out vec4 vWorldPosition;"),s.push("flat out uvec4 vFlags2;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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 al=p.vec3(),ll=p.vec3(),hl=p.vec3(),cl=p.vec3(),Al=p.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,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=e.pickViewMatrix||o.viewMatrix;let f,m;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const t=al;if(h){const e=ll;p.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],f=S(d,t,Al),m=hl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),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._uWorldMatrix,!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 E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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 pl=p.vec3(),dl=p.vec3(),fl=p.vec3(),ml=p.vec3(),El=p.vec3(),yl=p.mat4();class gl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=pl;let E,y;m[0]=p.safeInv(d[3]-d[0])*p.MAX_INT,m[1]=p.safeInv(d[4]-d[1])*p.MAX_INT,m[2]=p.safeInv(d[5]-d[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(m[0]),e.snapPickCoordinateScale[1]=p.safeInv(m[1]),e.snapPickCoordinateScale[2]=p.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=dl;if(g){const e=p.transformPoint3(A,h,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]+=c[0],t[1]+=c[1],t[2]+=c[2],E=S(f,t,yl),y=ml,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(_,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(_,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(_,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uSnapVectorA;"),s.push("uniform vec2 uSnapInvVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),s.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vl=p.vec3(),Il=p.vec3(),_l=p.vec3(),Tl=p.vec3(),Rl=p.vec3(),Pl=p.mat4();class Dl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=vl;let E,y;m[0]=p.safeInv(d[3]-d[0])*p.MAX_INT,m[1]=p.safeInv(d[4]-d[1])*p.MAX_INT,m[2]=p.safeInv(d[5]-d[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(m[0]),e.snapPickCoordinateScale[1]=p.safeInv(m[1]),e.snapPickCoordinateScale[2]=p.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=Il;if(g){const e=_l;p.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],E=S(f,t,Pl),y=Tl,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uVectorAB;"),s.push("uniform vec2 uInverseVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),s.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" } else {"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const bl=p.vec3(),Cl=p.vec3(),Nl=p.vec3(),Ol=p.vec3(),Sl=p.mat4();class xl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=bl;if(h){const t=Cl;p.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,Sl),m=Nl,m[0]=o.eye[0]-e[0],m[1]=o.eye[1]-e[1],m[2]=o.eye[2]-e[2]}else f=d,m=o.eye;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" } else {"),s.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const wl=p.vec3(),Bl=p.vec3(),Ml=p.vec3(),Fl=p.vec3(),Ll=p.mat4();class Ul{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=wl;if(m){const t=p.transformPoint3(A,h,Bl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=S(r.viewMatrix,e,Ll),f=Ml,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),s&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 Hl=p.vec3(),Gl=p.vec3(),Vl=p.vec3(),kl=p.vec3(),jl=p.mat4();class Ql{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const m=0!==l[0]||0!==l[1]||0!==l[2],E=0!==h[0]||0!==h[1]||0!==h[2];if(m||E){const e=Hl;if(m){const t=Gl;p.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],d=S(u,e,jl),f=Vl,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=u,f=o.eye;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,A),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,i.worldNormalMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;t0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&ce.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec3 normal;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 worldNormalMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 viewNormalMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),ce.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(ce.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&ce.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&&ce.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let e=0;e 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&&ce.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 Wl=p.vec3(),zl=p.vec3(),Kl=p.vec3(),Yl=p.vec3();p.vec4();const Xl=p.mat4();class Zl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=Wl;if(m){const t=p.transformPoint3(A,h,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]+=c[0],e[1]+=c[1],e[2]+=c[2],d=S(r.viewMatrix,e,Xl),f=Kl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("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;"),s&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),s&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;"),s){i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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(${p.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ql{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._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=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 Qa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new nl(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Zl(this._scene)),this._vertexDepthRenderer||(this._vertexDepthRenderer=new gl(this._scene)),this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Dl(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new La(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new La(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Qa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ul(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ql(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Za(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new tl(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new nl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Zl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Zl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new gl(this._scene)),this._vertexDepthRenderer}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Dl(this._scene)),this._snapDepthBufInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new xl(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._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Jl={};class $l{constructor(){this.positionsCompressed=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class eh{constructor(){this.texturePerObjectIdColorsAndFlags=null,this.texturePerObjectIdOffsets=null,this.texturePerObjectIdPositionsDecodeMatrix=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,s,i,r,o){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,s,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,i,3),this.texturePerObjectIdOffsets.bindTexture(e,o,4)}bindTriangleIndicesTextures(e,t,s,i){this.indicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.indicesPerBitnessTextures[i].bindTexture(e,s,6)}bindEdgeIndicesTextures(e,t,s,i){this.edgeIndicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[i].bindTexture(e,s,6)}}class th{constructor(e,t,s,i,r=null){this._gl=e,this._texture=t,this._textureWidth=s,this._textureHeight=i,this._textureData=r}bindTexture(e,t,s){return e.bindTexture(t,this,s)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const sh={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(sh,null,4));let e=0;Object.keys(sh).forEach((t=>{t.startsWith("size")&&(e+=sh[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/sh.totalPolygons).toFixed(2)}`);let t={};Object.keys(sh).forEach((s=>{s.startsWith("size")&&(t[s]=`${(sh[s]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class ih{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,s,i,r,o,n){const a=t.length;this.numPortions=a;const l=4096,h=Math.ceil(a/512);if(0===h)throw"texture height===0";const c=new Uint8Array(16384*h);sh.sizeDataColorsAndFlags+=c.byteLength,sh.numberOfTextures++;for(let e=0;e>24&255,i[e]>>16&255,i[e]>>8&255,255&i[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,h),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,h,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new th(e,A,l,h,c)}generateTextureForObjectOffsets(e,t){const s=512,i=Math.ceil(t/s);if(0===i)throw"texture height===0";const r=new Float32Array(1536*i).fill(0);sh.sizeDataTextureOffsets+=r.byteLength,sh.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,s,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,i,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 th(e,o,s,i,r)}generateTextureForPositionsDecodeMatrices(e,t,s){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const r=2048,o=Math.ceil(i/512),n=new Float32Array(8192*o);sh.sizeDataPositionDecodeMatrices+=n.byteLength,sh.numberOfTextures++;const a=p.mat4();for(let e=0;e{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jl[t],s._destroy()}))),s}(e.scene),this.model=e,this._buffer=new $l,this._dataTextureState=new eh,this._dataTextureGenerator=new ih,this._state=new Ge({origin:p.vec3(t.origin),metallicRoughnessBuf:null,positionsDecodeMatrix:p.mat4(),textureState:this._dataTextureState,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.aabb=p.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&sh.cannotCreatePortion.because10BitsObjectId++;let s=this._numPortions+t<=65536;const i=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[i]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let i=0,r=0;e.buckets.forEach((e=>{i+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+i>16777216||t+r>16777216)&&sh.cannotCreatePortion.becauseTextureSize++,s&&=this._state.numVertices+i<=16777216&&t+r<=16777216}return s}createPortion(e){if(this._finalized)throw"Already finalized";const t=[],s=e.worldAABB;e.buckets.forEach(((i,r)=>{const o=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#${r}`:`${e.id}#${r}`;let n=this._bucketGeometries[o];n||(n=this._createBucketGeometry(e,i),this._bucketGeometries[o]=n);const a=p.collapseAABB3(lh),l=this._createSubPortion(e,n,i,a);p.expandAABB3(s,a),t.push(l)}));const i=this._state.origin;0===i[0]&&0===i[1]&&0===i[2]||(s[0]+=i[0],s[1]+=i[1],s[2]+=i[2],s[3]+=i[0],s[4]+=i[1],s[5]+=i[2]),p.expandAABB3(this.aabb,s);const r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(t),this.model.numPortions++,r}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;sh.overheadSizeAlignementIndices+=2*(e-t.indices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;sh.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.edgeIndices),t.edgeIndices=s}const s=t.positionsCompressed,i=t.indices,r=t.edgeIndices,o=this._buffer,n=o.positionsCompressed.length/3,a=s.length/3;for(let e=0,t=s.length;e0){let e,s=3*t.numTriangles;t.numVertices<=256?(e=h.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=s,sh.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=h.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=s,sh.totalPolygons16Bits+=t.numTriangles):(e=h.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=s,sh.totalPolygons32Bits+=t.numTriangles),sh.totalPolygons+=t.numTriangles;for(let s=0;s0){let e,s=2*t.numEdges;t.numVertices<=256?(e=h.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=s,sh.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=h.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=s,sh.totalEdges16Bits+=t.numEdges):(e=h.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=s,sh.totalEdges32Bits+=t.numEdges),sh.totalEdges+=t.numEdges;for(let s=0;s0&&(t.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId8Bits)),i.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId16Bits)),i.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId32Bits)),i.indices8Bits.length>0&&(t.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,i.indices8Bits)),i.indices16Bits.length>0&&(t.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,i.indices16Bits)),i.indices32Bits.length>0&&(t.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,i.indices32Bits)),i.edgeIndices8Bits.length>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(s,i.edgeIndices8Bits)),i.edgeIndices16Bits.length>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(s,i.edgeIndices16Bits)),i.edgeIndices32Bits.length>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(s,i.edgeIndices32Bits)),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,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(console.info("_uploadDeferredFlags"),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.texturePerObjectIdColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdColorsAndFlags._textureWidth,t.texturePerObjectIdColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectIdColorsAndFlags._textureData),e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdOffsets._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdOffsets._textureWidth,t.texturePerObjectIdOffsets._textureHeight,e.RGB,e.FLOAT,t.texturePerObjectIdOffsets._textureData)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdColorsAndFlags._texture),i.texSubImage2D(i.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,i.RGBA_INTEGER,i.UNSIGNED_BYTE,nh)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,i=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),d.bindTexture(d.TEXTURE_2D,p.texturePerObjectIdColorsAndFlags._texture),d.texSubImage2D(d.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,d.RGBA_INTEGER,d.UNSIGNED_BYTE,nh))}_setDeferredFlags(){}_setFlags2(e,t,s=!1){const i=this._portionToSubPortionsMap[e];for(let e=0,r=i.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectIdColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,nh))}_setDeferredFlags2(){}setOffset(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdOffsets._texture),i.texSubImage2D(i.TEXTURE_2D,0,0,e,1,1,i.RGB,i.FLOAT,ah))}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._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,fr.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,fr.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._dataTextureRenderers.depthRenderer&&this._dataTextureRenderers.depthRenderer.drawLayer(t,this,fr.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._dataTextureRenderers.normalsRenderer&&this._dataTextureRenderers.normalsRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,fr.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._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,fr.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,fr.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,fr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,fr.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,fr.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.occlusionRenderer&&this._dataTextureRenderers.occlusionRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.shadowRenderer&&this._dataTextureRenderers.shadowRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,fr.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,fr.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,fr.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,fr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,fr.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}}const uh=p.vec3();p.mat4();const ph=p.vec3([1,1,1]),dh=p.vec3([0,0,0]),fh=p.vec3([0,0,0]),mh=p.identityQuaternion(),Eh=p.identityMat4(),yh="defaultColorTexture",gh="defaultMetalRoughTexture",vh="defaultNormalsTexture",Ih="defaultEmissiveTexture",_h="defaultOcclusionTexture",Th="defaultTextureSet",Rh=new Uint8Array([255,255,255]);class Ph extends N{constructor(e,t={}){super(e,t),this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!0,this._vboBatchingLayerScratchMemory=(dr++,pr),this._textureTranscoder=t.textureTranscoder||function(e){const t=e.scene.id;let s=Ia[t];return s||(s=new va({viewer:e}),Ia[t]=s,e.scene.on("destroyed",(()=>{delete Ia[t],s.destroy()}))),s}(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=p.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._entityList=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this._scheduledMeshes={},this.renderFlags=new js,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._edgeThreshold=t.edgeThreshold||10,this._origin=p.vec3(t.origin||[0,0,0]),this._position=p.vec3(t.position||[0,0,0]),this._rotation=p.vec3(t.rotation||[0,0,0]),this._quaternion=p.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=p.vec4(t.quaternion||[0,0,0,1]),t.rotation&&p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=p.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=p.mat4(),this._worldRotationMatrixConjugate=p.mat4(),this._matrix=p.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=p.mat4(),p.inverseMat4(this._matrix,this._worldNormalMatrix),p.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=p.mat4(),this._viewNormalMatrix=p.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._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}_createDefaultTextureSet(){const e=new pa({id:yh,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new pa({id:gh,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),s=new pa({id:vh,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),i=new pa({id:Ih,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new pa({id:_h,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=s,this._textures.defaultEmissiveTexture=i,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new ua({id:Th,model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:s,emissiveTexture:i,occlusionTexture:r})}get isPerformanceModel(){return!0}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),p.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Eh),p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),p.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),p.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),p.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),p.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0}_setLocalAABBDirty(){for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,s=new Uint8Array(t.length);for(let e=0,i=t.length;e{l.setImage(h,{minFilter:s,magFilter:i,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},h.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 pa({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 s,i,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(s=this._textures[e.colorTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(i=this._textures[e.metallicRoughnessTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else i=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 ua({id:t,model:this,colorTexture:s,metallicRoughnessTexture:i,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});this._textureSets[t]=a}createMesh(e){if(void 0===e.id||null===e.id)return void this.error("[createMesh] SceneModel.createMesh() config missing: id");if(this._scheduledMeshes[e.id])return void this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`);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 void this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`);if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),null;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),null;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'"),null;const t=!!this._dtxEnabled&&("triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive);if(e.origin=e.origin?p.addVec3(this._origin,e.origin,p.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||ph,s=e.position||dh,i=e.rotation||fh;p.eulerToQuaternion(i,"XYZ",mh),e.meshMatrix=p.composeMat4(s,mh,t,p.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Jr(e.positionsDecodeBoundary,p.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])]):Rh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=p.vec3(),s=[];w(e.positions,s,t)&&(e.positions=s,e.origin=p.addVec3(e.origin,t,t))}if(e.positions){const t=p.collapseAABB3();e.positionsDecodeMatrix=p.mat4(),p.expandAABB3Points3(t,e.positions),e.positionsCompressed=qr(e.positions,t,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ut(e.positions,e.indices,null,2):e.edgeIndices=ut(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=Dh(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];w(e.positions,t,uh)&&(e.positions=t,e.origin=p.addVec3(e.origin,uh,p.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ut(e.positions,e.indices,null,2):e.edgeIndices=ut(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return void this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`)}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return void this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)");if(e.geometry=this._geometries[e.geometryId],!e.geometry)return void this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`);if(e.origin=e.origin?p.addVec3(this._origin,e.origin,p.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.matrix)e.meshMatrix=e.matrix.slice();else{const t=e.scale||ph,s=e.position||dh,i=e.rotation||fh;p.eulerToQuaternion(i,"XYZ",mh),e.meshMatrix=p.composeMat4(s,mh,t,p.mat4())}if(!!this._dtxEnabled&&("triangles"===e.geometry.primitive||"solid"===e.geometry.primitive||"surface"===e.geometry.primitive)){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])]):Rh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=Dh(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Rh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId]),function(e){if(e.obb=p.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){const t=p.collapseAABB3();p.expandAABB3Points3(t,e.positionsCompressed),gt.decompressAABB(t,e.positionsDecodeMatrix),p.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){const t=p.collapseAABB3();p.expandAABB3Points3(t,e.positions),p.AABB3ToOBB3(t,e.obb)}}(e.geometry)}e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createMesh(e){const t=new ur(this,e.id,e.color,e.opacity);t.pickId=this.scene._renderer.getPickID(t);const s=t.pickId,i=s>>24&255,r=s>>16&255,o=s>>8&255,n=255&s;switch(e.pickColor=new Uint8Array([n,o,r,i]),e.worldAABB=p.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=p.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e);break;case 1:t.layer=this._getVBOBatchingLayer(e);break;case 0:t.layer=this._getVBOInstancingLayer(e)}t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.numPrimitives=e.numPrimitives,p.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t,this._meshList.push(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 s=0,i=e.buckets.length;s>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,s=e.origin,i=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${i}.${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":console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`),n=new gn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!1});break;case"solid":console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`),n=new gn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!0});break;case"lines":console.info(`[SceneModel ${this.id}]: creating LinesInstancingLayer`),n=new Ln({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0});break;case"points":console.info(`[SceneModel ${this.id}]: creating PointsInstancingLayer`),n=new Aa({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=p.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=p.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=M),this._pickable&&!1!==e.pickable&&(t|=L),this._culled&&!1!==e.culled&&(t|=F),this._clippable&&!1!==e.clippable&&(t|=U),this._collidable&&!1!==e.collidable&&(t|=H),this._edges&&!1!==e.edges&&(t|=j),this._xrayed&&!1!==e.xrayed&&(t|=G),this._highlighted&&!1!==e.highlighted&&(t|=V),this._selected&&!1!==e.selected&&(t|=k),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];const s=p.collapseAABB3();for(let i=0,r=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,s=this.layerList.length;t0)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 s=0,i=t.visibleLayers.length;s65536?16:8)}else n=[{positionsCompressed:i,indices:r,edgeIndices:o}];return n}const bh=p.vec4(),Ch=p.vec4(),Nh=p.vec3(),Oh=p.vec3(),Sh=p.vec3(),xh=p.vec4(),wh=p.vec4(),Bh=p.vec4();class Mh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,s){let i=!1;const r=this._scene.camera;if(e){const t=p.subVec3(e,r.eye,Nh);i=p.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=p.vec3();p.decomposeMat4(p.inverseMat4(this._scene.viewer.camera.viewMatrix,p.mat4()),t,p.vec4(),p.vec3());const s=p.distVec3(t,e);let i=Math.tan(Math.PI/500)*s*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(i/=this._scene.camera.ortho.scale/2),x(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Di(this._scene,ii({radius:i})),this._pivotSphere=new ei(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){p.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,p.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const s=t.boundary,i=s[2],r=s[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*i/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&&(x(this.getPivotPos(),this._rtcCenter,this._rtcPos),p.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 bt(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=p.lookAtMat4v(e.eye,e.look,e.worldUp);p.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const s=this.getPivotPos();this._cameraOffset[2]+=p.distVec3(e.eye,s),t=p.inverseMat4(t);const i=p.transformVec3(t,this._cameraOffset),r=p.vec3();if(p.subVec3(e.eye,s,r),p.addVec3(r,i),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=p.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=p.normalizeVec3(p.subVec3(e.look,e.eye,Fh)),s=p.cross3Vec3(t,e.worldUp,Lh);return p.sqLenVec3(s)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,s=Math.abs(p.distVec3(this._scene.center,t.eye)),i=t.project.transposedMatrix,r=i.subarray(8,12),o=i.subarray(12),n=[0,0,-1,1],a=p.dotVec4(n,r)/p.dotVec4(n,o),l=Hh;t.project.unproject(e,a,Gh,Vh,l);const h=p.normalizeVec3(p.subVec3(l,t.eye,Fh)),c=p.addVec3(t.eye,p.mulVec3Scalar(h,s,Lh),Uh);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const s=this._scene.camera;var i=-e;const r=-t;1===s.worldUp[2]&&(i=-i),this._azimuth+=.01*-i,this._polar+=.01*r,this._polar=p.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===s.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=p.lenVec3(p.subVec3(s.look,s.eye,p.vec3())),a=this.getPivotPos();p.addVec3(o,a);let l=p.lookAtMat4v(o,a,s.worldUp);l=p.inverseMat4(l);const h=p.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];s.eye=[l[12],l[13],l[14]],p.subVec3(s.eye,p.mulVec3Scalar(c,n),s.look),s.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 jh{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=p.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.snapPick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&e.snappedWorldPos?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents=!0):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,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._needFireEvents=!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=!0):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,cursorPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new ue;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.snappedWorldPos,e.cursorPos=this.pickCursorPos,e.canvasPos=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=!1}}destroy(){}}const Qh=p.vec2();class Wh{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController;let n,a,l,h=0,c=0,A=0,u=0,d=!1;const f=p.vec3();let m=!0;const E=this._scene.canvas.canvas,y=[];function g(e=!0){E.style.cursor="move",h=i.pointerCanvasPos[0],c=i.pointerCanvasPos[1],A=i.pointerCanvasPos[0],u=i.pointerCanvasPos[1],e&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(d=!0,f.set(o.pickResult.worldPos)):d=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!1}),E.addEventListener("mousedown",this._mouseDownHandler=t=>{if(s.active&&s.pointerEnabled)switch(t.which){case 1:y[e.input.KEY_SHIFT]||s.planView?(n=!0,g()):(n=!0,g(!1));break;case 2:a=!0,g();break;case 3:l=!0,s.panRightClick&&g()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!s.active||!s.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],A=t[3],u=i.pointerCanvasPos[0],m=i.pointerCanvasPos[1];if(y[e.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l){const t=u-h,s=m-c,i=e.camera;if("perspective"===i.projection){const o=Math.abs(d?p.lenVec3(p.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/A,r.panDeltaY+=1.5*s*o/A}else r.panDeltaX+=.5*i.ortho.scale*(t/A),r.panDeltaY+=.5*i.ortho.scale*(s/A)}else!n||a||l||s.planView||(s.firstPerson?(r.rotateDeltaY-=(u-h)/o*s.dragRotationRate/2,r.rotateDeltaX+=(m-c)/A*(s.dragRotationRate/4)):(r.rotateDeltaY-=(u-h)/o*(1.5*s.dragRotationRate),r.rotateDeltaX+=(m-c)/A*(1.5*s.dragRotationRate)));h=u,c=m}),E.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{s.active&&s.pointerEnabled&&i.mouseover&&(m=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),E.addEventListener("mouseup",this._mouseUpHandler=e=>{if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){let s=e.target,i=0,r=0,o=0,n=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,o+=s.scrollLeft,n+=s.scrollTop,s=s.offsetParent;t[0]=e.pageX+o-i,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Qh);const s=Qh[0],i=Qh[1];Math.abs(s-A)<3&&Math.abs(i-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Qh,event:e},!0)}E.style.removeProperty("cursor")}}),E.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.active&&s.pointerEnabled});const v=1/60;let I=null;E.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==I?t-I:0;I=t,o>.05&&(o=.05),o{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),h=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),A=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||h||c||A))return;const u=e.aabb,d=p.getAABB3Diag(u);p.getAABB3Center(u,zh);const f=Math.abs(d/Math.tan(t.cameraFlight.fitFOV*p.DEGTORAD)),m=1.1*d;qh.orthoScale=m,n?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldRight,f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):a?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldForward,f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):l?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldRight,-f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):h?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldForward,-f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):c?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldUp,f,Kh),Zh)),qh.look.set(zh),qh.up.set(p.normalizeVec3(p.mulVec3Scalar(o.worldForward,1,Yh),Xh))):A&&(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldUp,-f,Kh),Zh)),qh.look.set(zh),qh.up.set(p.normalizeVec3(p.mulVec3Scalar(o.worldForward,-1,Yh)))),!s.firstPerson&&s.followPointer&&t.pivotController.setPivotPos(zh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(qh,(()=>{t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(qh),t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class $h{constructor(e,t,s,i,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,h=!1;const c=this._scene.canvas.canvas,A=s=>{let i;s&&s.worldPos&&(i=s.worldPos);const r=s&&s.entity?s.entity.aabb:e.aabb;if(i){const s=e.camera;p.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(l||h)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),A=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||A||u||p)if(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(h=!0);if(1===t.which&&s.active&&s.pointerEnabled&&(i.mouseDownClientX=t.clientX,i.mouseDownClientY=t.clientY,i.mouseDownCursorX=i.pointerCanvasPos[0],i.mouseDownCursorY=i.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(h=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!s.active||!s.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-i.mouseDownClientX)>3||Math.abs(r.clientY-i.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),h=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),d=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||u||d||f))return(l||h||c)&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!s.firstPerson&&s.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0),this._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo||u||d,o.schedulePickSurface=o.schedulePickEntity&&d,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),s.doublePickFlyTo&&(A(o.pickResult),!s.firstPerson&&s.followPointer)){const e=o.pickResult.entity.aabb,s=p.getAABB3Center(e);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:i.pointerCanvasPos},!0),s.doublePickFlyTo&&(A(),!s.firstPerson&&s.followPointer)){const s=e.aabb,i=p.getAABB3Center(s);t.pivotController.setPivotPos(i),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 ec{constructor(e,t,s,i,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=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&i.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(i=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&(n[i]=!1,i===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const h=t.cameraControl,c=a.deltaTime/1e3;if(!s.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,n),i=h._isKeyDownForAction(h.ROTATE_Y_NEG,n),o=h._isKeyDownForAction(h.ROTATE_X_POS,n),a=h._isKeyDownForAction(h.ROTATE_X_NEG,n),l=c*s.keyboardRotationRate;(e||i||o||a)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:i&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!s.firstPerson&&s.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,n),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,n);if(e||o){const n=c*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(i.followPointerDirty=!0,l=!1)}}const A=h._isKeyDownForAction(h.PAN_FORWARDS,n),u=h._isKeyDownForAction(h.PAN_BACKWARDS,n),p=h._isKeyDownForAction(h.PAN_LEFT,n),d=h._isKeyDownForAction(h.PAN_RIGHT,n),f=h._isKeyDownForAction(h.PAN_UP,n),m=h._isKeyDownForAction(h.PAN_DOWN,n),E=(n[o.KEY_ALT]?.3:1)*c*s.keyboardPanRate;(A||u||p||d||f||m)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=E:f&&(r.panDeltaY+=-E),d?r.panDeltaX+=-E:p&&(r.panDeltaX+=E),u?r.panDeltaZ+=E:A&&(r.panDeltaZ+=-E))}))}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 tc=.001,sc=p.vec3();class ic{constructor(e,t,s,i,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let h=1,c=1,A=null;this._onTick=e.on("tick",(()=>{if(!s.active||!s.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta){i.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{i.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{oc(e,o,i.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{s.active&&s.pointerEnabled&&(oc(e,o,i.pointerCanvasPos),i.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{s.active&&s.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 oc(e,t,s){if(e){const{x:i,y:r}=t.getBoundingClientRect();s[0]=e.clientX-i,s[1]=e.clientY-r}else e=window.event,s[0]=e.x,s[1]=e.y;return s}const nc=function(e,t){if(e){let s=e.target,i=0,r=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-i,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class ac{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=p.vec2(),l=p.vec2(),h=p.vec2(),c=p.vec2(),A=[],u=this._scene.canvas.canvas;let d=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!s.active||!s.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(i.touchStartTime=Date.now(),1===r.length&&1===l.length&&(nc(r[0],a),s.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),s.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!s.firstPerson&&n.startPivot()&&n.showPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),!s.firstPerson&&n.startPivot()&&n.showPivot()))));A.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],m=t.touches;if(t.touches.length===d){if(1===d){nc(m[0],l),p.subVec2(l,A[0],c);const t=c[0],o=c[1];if(null!==i.longTouchTimeout&&(Math.abs(t)>s.longTapRadius||Math.abs(o)>s.longTapRadius)&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),s.planView){const i=e.camera;if("perspective"===i.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*s.touchPanRate,r.panDeltaY+=o*n/u*s.touchPanRate}else r.panDeltaX+=.5*i.ortho.scale*(t/u)*s.touchPanRate,r.panDeltaY+=.5*i.ortho.scale*(o/u)*s.touchPanRate}else r.rotateDeltaY-=t/a*(1*s.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*s.dragRotationRate)}else if(2===d){const t=m[0],n=m[1];nc(t,l),nc(n,h);const a=p.geometricMeanVec2(A[0],A[1]),c=p.geometricMeanVec2(l,h),d=p.vec2();p.subVec2(a,c,d);const f=d[0],E=d[1],y=e.camera,g=p.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),v=(p.distVec2(A[0],A[1])-g)*s.touchDollyRate;if(r.dollyDelta=v,Math.abs(v)<1)if("perspective"===y.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,i=Math.abs(p.lenVec3(p.subVec3(t,e.camera.eye,[])))*Math.tan(y.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*i/u*s.touchPanRate,r.panDeltaY-=E*i/u*s.touchPanRate}else r.panDeltaX-=.5*y.ortho.scale*(f/u)*s.touchPanRate,r.panDeltaY-=.5*y.ortho.scale*(E/u)*s.touchPanRate;i.pointerCanvasPos=c}for(let e=0;e{let i;s&&s.worldPos&&(i=s.worldPos);const r=s?s.entity.aabb:e.aabb;if(i){const s=e.camera;p.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!s.active||!s.pointerEnabled)return;null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,lc(r[0],h);const o=h[0],n=h[1],l=r[0].pageX,A=r[0].pageY;i.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(A)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),i.longTouchTimeout=null}),s.longTapTimeout)}else c=-1;for(;l.length{if(!s.active||!s.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(A>-1&&c-A<325?(lc(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),s.doublePickFlyTo&&d(o.pickResult)):(n.fire("doublePickedNothing"),s.doublePickFlyTo&&d()),A=-1):p.distVec2(l[0],h)<4&&(lc(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"),A=t),c=-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:p.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:p.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const s=this.scene;this._controllers={cameraControl:this,pickController:new jh(this,this._configs),pivotController:new kh(s,this._configs),panController:new Mh(s),cameraFlight:new lr(this,{duration:.5})},this._handlers=[new rc(this.scene,this._controllers,this._configs,this._states,this._updates),new ac(this.scene,this._controllers,this._configs,this._states,this._updates),new Wh(this.scene,this._controllers,this._configs,this._states,this._updates),new Jh(this.scene,this._controllers,this._configs,this._states,this._updates),new $h(this.scene,this._controllers,this._configs,this._states,this._updates),new hc(this.scene,this._controllers,this._configs,this._states,this._updates),new ec(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new ic(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,s={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":s[this.PAN_LEFT]=[t.KEY_A],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_Z],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":s[this.PAN_LEFT]=[t.KEY_Q],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_W],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=s}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const s=this._keyMap[e];if(!s)return!1;t||(t=this.scene.input.keyDown);for(let e=0,i=s.length;e0?mc(t):null,n=s&&s.length>0?mc(s):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&i.push(e.id);const s=e.children;if(s)for(var r=0,l=s.length;r>t;s.sort(ba);const i=new Int32Array(e.length);for(let t=0,r=s.length;te[t+1]){let s=e[t];e[t]=e[t+1],e[t+1]=s}Ca=new Int32Array(e),t.sort(Na);const s=new Int32Array(e.length);for(let i=0,r=t.length;it){let s=e;e=t,t=s}function s(s,i){return s!==e?e-s:i!==t?t-i:0}let i=0,r=(o.length>>1)-1;for(;i<=r;){const e=r+i>>1,t=s(o[2*e],o[2*e+1]);if(t>0)i=e+1;else{if(!(t<0))return e;r=e-1}}return-i-1}const a=new Int32Array(o.length/2);a.fill(0);const l=i.length/3;if(l>8*(1<u.maxNumPositions&&(u=A()),u.bucketNumber>8)return[e];let d;-1===h[l]&&(h[l]=u.numPositions++,u.positionsCompressed.push(i[3*l]),u.positionsCompressed.push(i[3*l+1]),u.positionsCompressed.push(i[3*l+2])),-1===h[c]&&(h[c]=u.numPositions++,u.positionsCompressed.push(i[3*c]),u.positionsCompressed.push(i[3*c+1]),u.positionsCompressed.push(i[3*c+2])),-1===h[p]&&(h[p]=u.numPositions++,u.positionsCompressed.push(i[3*p]),u.positionsCompressed.push(i[3*p+1]),u.positionsCompressed.push(i[3*p+2])),u.indices.push(h[l]),u.indices.push(h[c]),u.indices.push(h[p]),(d=n(l,c))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(l,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]])),(d=n(c,p))>=0&&0===a[d]&&(a[d]=1,u.edgeIndices.push(h[o[2*d]]),u.edgeIndices.push(h[o[2*d+1]]))}const p=t/8*2,d=t/8,f=2*i.length+(r.length+o.length)*p;let m=0,E=-i.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*d,E+=e.positionsCompressed.length/3})),m>f?[e]:(s&&function(e,t){const s={};let i=0;e.forEach((e=>{const t=e.indices,r=e.edgeIndices,o=e.positionsCompressed;for(let e=0,i=t.length;e0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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,s=e._lightsState;if(this._program=new ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uLightAmbient=i.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=s.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 sceneModelWorldMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),o.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),o.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform highp sampler2D uTextureModelMatrices;"),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=s.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, 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 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, 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 (uTexturePerObjectIdColorsAndFlags, 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*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),o.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),o.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),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=s.lights.length;e0,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"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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;"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ua=new Float32Array([1,1,1]),Ha=p.vec3(),Ga=p.vec3(),Va=p.vec3(),ka=p.vec3(),ja=p.mat4();class Qa{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=Ha;if(h){const t=Ga;p.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,ja),m=Va,m[0]=r.eye[0]-e[0],m[1]=r.eye[1]-e[1],m[2]=r.eye[2]-e[2]}else f=d,m=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),s===fr.SILHOUETTE_XRAYED){const e=i.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.SILHOUETTE_HIGHLIGHTED){const e=i.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.SILHOUETTE_SELECTED){const e=i.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,Ua);if(i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const E=i._sectionPlanesState.sectionPlanes.length;if(E>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.y) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("} else {"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("viewNormal = -viewNormal;"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 Wa=new Float32Array([0,0,0,1]),za=p.vec3(),Ka=p.vec3(),Ya=p.vec3(),Xa=p.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,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=za;if(m){const t=p.transformPoint3(A,h,Ka);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,Xa)}else f=d;if(n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),s===fr.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===fr.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],s)}else n.uniform4fv(this._uColor,Wa);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 qa=p.vec3(),Ja=p.vec3(),$a=p.vec3(),el=p.mat4();class tl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=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._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=qa;if(m){const t=p.transformPoint3(A,h,Ja);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,el)}else f=d;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureEdgesColorRenderer"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled,s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.z) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push(" vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vec4 rgb = vec4(color.rgba);"),s.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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=p.vec3(),il=p.vec3(),rl=p.vec3(),ol=p.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,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i;let d,f;l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=sl;if(m){const t=p.transformPoint3(A,h,il);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=S(o.viewMatrix,e,ol),f=rl,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("smooth out vec4 vWorldPosition;"),s.push("flat out uvec4 vFlags2;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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 al=p.vec3(),ll=p.vec3(),hl=p.vec3(),cl=p.vec3(),Al=p.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,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=e.pickViewMatrix||o.viewMatrix;let f,m;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const t=al;if(h){const e=ll;p.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],f=S(d,t,Al),m=hl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),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._uWorldMatrix,!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 E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("uniform vec2 pickClipPos;"),s.push("uniform vec2 drawingBufferSize;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.w) != renderPass) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("} else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(worldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("} else {"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (viewNormal.z < 0.0) {"),s.push("position = positions[2 - (gl_VertexID % 3)];"),s.push("}"),s.push("}"),s.push("}"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 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 pl=p.vec3(),dl=p.vec3(),fl=p.vec3(),ml=p.vec3(),El=p.vec3(),yl=p.mat4();class gl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=pl;let E,y;m[0]=p.safeInv(d[3]-d[0])*p.MAX_INT,m[1]=p.safeInv(d[4]-d[1])*p.MAX_INT,m[2]=p.safeInv(d[5]-d[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(m[0]),e.snapPickCoordinateScale[1]=p.safeInv(m[1]),e.snapPickCoordinateScale[2]=p.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=dl;if(g){const e=p.transformPoint3(A,h,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]+=c[0],t[1]+=c[1],t[2]+=c[2],E=S(f,t,yl),y=ml,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(_,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(_,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(_,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uSnapVectorA;"),s.push("uniform vec2 uSnapInvVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),s.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out vec4 vViewPosition;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int edgeIndex = gl_VertexID / 2;"),s.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),s.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),s.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),s.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),s.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2.r;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vViewPosition = clipPos;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vl=p.vec3(),Il=p.vec3(),_l=p.vec3(),Tl=p.vec3(),Rl=p.vec3(),Pl=p.mat4();class Dl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=t.aabb,f=e.pickViewMatrix||o.viewMatrix,m=vl;let E,y;m[0]=p.safeInv(d[3]-d[0])*p.MAX_INT,m[1]=p.safeInv(d[4]-d[1])*p.MAX_INT,m[2]=p.safeInv(d[5]-d[2])*p.MAX_INT,e.snapPickCoordinateScale[0]=p.safeInv(m[0]),e.snapPickCoordinateScale[1]=p.safeInv(m[1]),e.snapPickCoordinateScale[2]=p.safeInv(m[2]),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const g=0!==h[0]||0!==h[1]||0!==h[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(g||v){const t=Il;if(g){const e=_l;p.transformPoint3(A,h,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],E=S(f,t,Pl),y=Tl,y[0]=o.eye[0]-t[0],y[1]=o.eye[1]-t[1],y[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else E=f,y=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,y),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,m),n.uniform1i(this._uRenderPass,s),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,E),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const I=r._sectionPlanesState.sectionPlanes.length;if(I>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 uVectorAB;"),s.push("uniform vec2 uInverseVectorAB;"),s.push("vec3 positions[3];"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),s.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("flat out uint vFlags2;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" } else {"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" viewNormal = -viewNormal;"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureSnapDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int uLayerNumber;"),s.push("uniform vec3 uCoordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let t=0,i=e.sectionPlanes.length;t 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const bl=p.vec3(),Cl=p.vec3(),Nl=p.vec3(),Ol=p.vec3(),Sl=p.mat4();class xl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=i,d=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,m;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets),h||0!==c[0]||0!==c[1]||0!==c[2]){const e=bl;if(h){const t=Cl;p.transformPoint3(A,h,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],f=S(d,e,Sl),m=Nl,m[0]=o.eye[0]-e[0],m[1]=o.eye[1]-e[1],m[2]=o.eye[2]-e[2]}else f=d,m=o.eye;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const E=r._sectionPlanesState.sectionPlanes.length;if(E>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*E,o=i.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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelWorldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),s.push("uniform highp sampler2D uTextureModelMatrices;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("vec3 positions[3];"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("void main(void) {"),s.push("int polygonIndex = gl_VertexID / 3;"),s.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),s.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),s.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),s.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),s.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),s.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),s.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),s.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),s.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),s.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),s.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),s.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),s.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),s.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),s.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),s.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),s.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),s.push("if (color.a == 0u) {"),s.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),s.push(" return;"),s.push("};"),s.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),s.push("vec3 position;"),s.push("position = positions[gl_VertexID % 3];"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),s.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" } else {"),s.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),s.push(" if (viewNormal.z < 0.0) {"),s.push(" position = positions[2 - (gl_VertexID % 3)];"),s.push(" }"),s.push(" }"),s.push("}"),s.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),s.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),s.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2.r;")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const wl=p.vec3(),Bl=p.vec3(),Ml=p.vec3(),Fl=p.vec3(),Ll=p.mat4();class Ul{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=wl;if(m){const t=p.transformPoint3(A,h,Bl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=S(r.viewMatrix,e,Ll),f=Ml,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),s&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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 Hl=p.vec3(),Gl=p.vec3(),Vl=p.vec3(),kl=p.vec3(),jl=p.mat4();class Ql{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const i=t.model,r=i.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:A}=i,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const m=0!==l[0]||0!==l[1]||0!==l[2],E=0!==h[0]||0!==h[1]||0!==h[2];if(m||E){const e=Hl;if(m){const t=Gl;p.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],d=S(u,e,jl),f=Vl,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else d=u,f=o.eye;n.uniform1i(this._uRenderPass,s),n.uniformMatrix4fv(this._uWorldMatrix,!1,A),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,i.worldNormalMatrix);const y=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,o=i.renderFlags;for(let t=0;t0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&ce.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec3 normal;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 worldNormalMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 viewNormalMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),ce.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("varying float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out vec4 vFlags2;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags2 = flags2;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(ce.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;")),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&ce.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&&ce.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),s){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let e=0;e 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&&ce.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 Wl=p.vec3(),zl=p.vec3(),Kl=p.vec3(),Yl=p.vec3();p.vec4();const Xl=p.mat4();class Zl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){const i=this._scene,r=i.camera,o=t.model,n=i.canvas.gl,a=t._state,l=a.textureState,h=t._state.origin,{position:c,rotationMatrix:A,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this._uTexturePerObjectIdPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this._uTexturePerObjectIdColorsAndFlags,this._uTextureModelMatrices,this._uTexturePerObjectIdOffsets);const m=0!==h[0]||0!==h[1]||0!==h[2],E=0!==c[0]||0!==c[1]||0!==c[2];if(m||E){const e=Wl;if(m){const t=p.transformPoint3(A,h,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]+=c[0],e[1]+=c[1],e[2]+=c[2],d=S(r.viewMatrix,e,Xl),f=Kl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else d=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,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 ge(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uSceneModelWorldMatrix=s.getLocation("sceneModelWorldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;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 sceneModelWorldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectIdPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uTexturePerObjectIdColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectIdOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform highp sampler2D uTextureModelMatrices;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("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;"),s&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.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 (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 positionsDecodeMatrix = mat4 (texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectIdPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelWorldMatrix * positionsDecodeMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*positionsDecodeMatrix)) * 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 = sceneModelWorldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),i.push("vec4 offset = vec4(texelFetch (uTexturePerObjectIdOffsets, objectIndexCoords, 0).rgb, 0.0);"),i.push("worldPosition.xyz = worldPosition.xyz + offset.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),s&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// 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;"),s){i.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e 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(${p.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ql{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._vertexDepthRenderer&&!this._vertexDepthRenderer.getValid()&&(this._vertexDepthRenderer.destroy(),this._vertexDepthRenderer=null),this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=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 Qa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new nl(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Zl(this._scene)),this._vertexDepthRenderer||(this._vertexDepthRenderer=new gl(this._scene)),this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Dl(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new La(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new La(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Qa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ul(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ql(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Za(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new tl(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new nl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Zl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Zl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ul(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new gl(this._scene)),this._vertexDepthRenderer}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Dl(this._scene)),this._snapDepthBufInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new xl(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._vertexDepthRenderer&&this._vertexDepthRenderer.destroy(),this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Jl={};class $l{constructor(){this.positionsCompressed=[],this.metallicRoughness=[],this.indices8Bits=[],this.indices16Bits=[],this.indices32Bits=[],this.edgeIndices8Bits=[],this.edgeIndices16Bits=[],this.edgeIndices32Bits=[],this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class eh{constructor(){this.texturePerObjectIdColorsAndFlags=null,this.texturePerObjectIdOffsets=null,this.texturePerObjectIdPositionsDecodeMatrix=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,s,i,r,o){this.texturePerObjectIdPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,s,2),this.texturePerObjectIdColorsAndFlags.bindTexture(e,i,3),this.texturePerObjectIdOffsets.bindTexture(e,o,4)}bindTriangleIndicesTextures(e,t,s,i){this.indicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.indicesPerBitnessTextures[i].bindTexture(e,s,6)}bindEdgeIndicesTextures(e,t,s,i){this.edgeIndicesPortionIdsPerBitnessTextures[i].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[i].bindTexture(e,s,6)}}class th{constructor(e,t,s,i,r=null){this._gl=e,this._texture=t,this._textureWidth=s,this._textureHeight=i,this._textureData=r}bindTexture(e,t,s){return e.bindTexture(t,this,s)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const sh={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(sh,null,4));let e=0;Object.keys(sh).forEach((t=>{t.startsWith("size")&&(e+=sh[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/sh.totalPolygons).toFixed(2)}`);let t={};Object.keys(sh).forEach((s=>{s.startsWith("size")&&(t[s]=`${(sh[s]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class ih{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,s,i,r,o,n){const a=t.length;this.numPortions=a;const l=4096,h=Math.ceil(a/512);if(0===h)throw"texture height===0";const c=new Uint8Array(16384*h);sh.sizeDataColorsAndFlags+=c.byteLength,sh.numberOfTextures++;for(let e=0;e>24&255,i[e]>>16&255,i[e]>>8&255,255&i[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,h),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,h,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new th(e,A,l,h,c)}generateTextureForObjectOffsets(e,t){const s=512,i=Math.ceil(t/s);if(0===i)throw"texture height===0";const r=new Float32Array(1536*i).fill(0);sh.sizeDataTextureOffsets+=r.byteLength,sh.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,s,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,i,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 th(e,o,s,i,r)}generateTextureForPositionsDecodeMatrices(e,t,s){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const r=2048,o=Math.ceil(i/512),n=new Float32Array(8192*o);sh.sizeDataPositionDecodeMatrices+=n.byteLength,sh.numberOfTextures++;const a=p.mat4();for(let e=0;e{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jl[t],s._destroy()}))),s}(e.scene),this.model=e,this._buffer=new $l,this._dataTextureState=new eh,this._dataTextureGenerator=new ih,this._state=new Ge({origin:p.vec3(t.origin),metallicRoughnessBuf:null,positionsDecodeMatrix:p.mat4(),textureState:this._dataTextureState,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.aabb=p.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&sh.cannotCreatePortion.because10BitsObjectId++;let s=this._numPortions+t<=65536;const i=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[i]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let i=0,r=0;e.buckets.forEach((e=>{i+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+i>16777216||t+r>16777216)&&sh.cannotCreatePortion.becauseTextureSize++,s&&=this._state.numVertices+i<=16777216&&t+r<=16777216}return s}createPortion(e){if(this._finalized)throw"Already finalized";const t=[],s=e.worldAABB;e.buckets.forEach(((i,r)=>{const o=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#${r}`:`${e.id}#${r}`;let n=this._bucketGeometries[o];n||(n=this._createBucketGeometry(e,i),this._bucketGeometries[o]=n);const a=p.collapseAABB3(lh),l=this._createSubPortion(e,n,i,a);p.expandAABB3(s,a),t.push(l)}));const i=this._state.origin;0===i[0]&&0===i[1]&&0===i[2]||(s[0]+=i[0],s[1]+=i[1],s[2]+=i[2],s[3]+=i[0],s[4]+=i[1],s[5]+=i[2]),p.expandAABB3(this.aabb,s);const r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(t),this.model.numPortions++,r}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;sh.overheadSizeAlignementIndices+=2*(e-t.indices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;sh.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const s=new Uint32Array(e);s.fill(0),s.set(t.edgeIndices),t.edgeIndices=s}const s=t.positionsCompressed,i=t.indices,r=t.edgeIndices,o=this._buffer,n=o.positionsCompressed.length/3,a=s.length/3;for(let e=0,t=s.length;e0){let e,s=3*t.numTriangles;t.numVertices<=256?(e=h.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=s,sh.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=h.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=s,sh.totalPolygons16Bits+=t.numTriangles):(e=h.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=s,sh.totalPolygons32Bits+=t.numTriangles),sh.totalPolygons+=t.numTriangles;for(let s=0;s0){let e,s=2*t.numEdges;t.numVertices<=256?(e=h.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=s,sh.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=h.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=s,sh.totalEdges16Bits+=t.numEdges):(e=h.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=s,sh.totalEdges32Bits+=t.numEdges),sh.totalEdges+=t.numEdges;for(let s=0;s0&&(t.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId8Bits)),i.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId16Bits)),i.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,i.perEdgeNumberPortionId32Bits)),i.indices8Bits.length>0&&(t.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,i.indices8Bits)),i.indices16Bits.length>0&&(t.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,i.indices16Bits)),i.indices32Bits.length>0&&(t.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,i.indices32Bits)),i.edgeIndices8Bits.length>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(s,i.edgeIndices8Bits)),i.edgeIndices16Bits.length>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(s,i.edgeIndices16Bits)),i.edgeIndices32Bits.length>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(s,i.edgeIndices32Bits)),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,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&V&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&G&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&j&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&L&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&V?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&G?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(console.info("_uploadDeferredFlags"),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.texturePerObjectIdColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdColorsAndFlags._textureWidth,t.texturePerObjectIdColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectIdColorsAndFlags._textureData),e.bindTexture(e.TEXTURE_2D,t.texturePerObjectIdOffsets._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectIdOffsets._textureWidth,t.texturePerObjectIdOffsets._textureHeight,e.RGB,e.FLOAT,t.texturePerObjectIdOffsets._textureData)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&L?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdColorsAndFlags._texture),i.texSubImage2D(i.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,i.RGBA_INTEGER,i.UNSIGNED_BYTE,nh)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,i=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),d.bindTexture(d.TEXTURE_2D,p.texturePerObjectIdColorsAndFlags._texture),d.texSubImage2D(d.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,d.RGBA_INTEGER,d.UNSIGNED_BYTE,nh))}_setDeferredFlags(){}_setFlags2(e,t,s=!1){const i=this._portionToSubPortionsMap[e];for(let e=0,r=i.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectIdColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,nh))}_setDeferredFlags2(){}setOffset(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,i=s.length;e=10&&this._beginDeferredFlags(),i.bindTexture(i.TEXTURE_2D,s.texturePerObjectIdOffsets._texture),i.texSubImage2D(i.TEXTURE_2D,0,0,e,1,1,i.RGB,i.FLOAT,ah))}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._dataTextureRenderers.colorRendererWithSAO&&this._dataTextureRenderers.colorRendererWithSAO.drawLayer(t,this,fr.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,fr.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._dataTextureRenderers.depthRenderer&&this._dataTextureRenderers.depthRenderer.drawLayer(t,this,fr.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._dataTextureRenderers.normalsRenderer&&this._dataTextureRenderers.normalsRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,fr.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.silhouetteRenderer&&this._dataTextureRenderers.silhouetteRenderer.drawLayer(t,this,fr.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._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,fr.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._dataTextureRenderers.edgesColorRenderer&&this._dataTextureRenderers.edgesColorRenderer.drawLayer(t,this,fr.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,fr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,fr.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,fr.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.occlusionRenderer&&this._dataTextureRenderers.occlusionRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.shadowRenderer&&this._dataTextureRenderers.shadowRenderer.drawLayer(t,this,fr.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,fr.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,fr.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,fr.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,fr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,fr.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}}const uh=p.vec3();p.mat4();const ph=p.vec3([1,1,1]),dh=p.vec3([0,0,0]),fh=p.vec3([0,0,0]),mh=p.identityQuaternion(),Eh=p.identityMat4(),yh="defaultColorTexture",gh="defaultMetalRoughTexture",vh="defaultNormalsTexture",Ih="defaultEmissiveTexture",_h="defaultOcclusionTexture",Th="defaultTextureSet",Rh=new Uint8Array([255,255,255]);class Ph extends N{constructor(e,t={}){super(e,t),this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!0,this._vboBatchingLayerScratchMemory=(dr++,pr),this._textureTranscoder=t.textureTranscoder||function(e){const t=e.scene.id;let s=Ia[t];return s||(s=new va({viewer:e}),Ia[t]=s,e.scene.on("destroyed",(()=>{delete Ia[t],s.destroy()}))),s}(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=p.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._entityList=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this._scheduledMeshes={},this.renderFlags=new js,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._edgeThreshold=t.edgeThreshold||10,this._origin=p.vec3(t.origin||[0,0,0]),this._position=p.vec3(t.position||[0,0,0]),this._rotation=p.vec3(t.rotation||[0,0,0]),this._quaternion=p.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=p.vec4(t.quaternion||[0,0,0,1]),t.rotation&&p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=p.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=p.mat4(),this._worldRotationMatrixConjugate=p.mat4(),this._matrix=p.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=p.mat4(),p.inverseMat4(this._matrix,this._worldNormalMatrix),p.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=p.mat4(),this._viewNormalMatrix=p.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._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}_createDefaultTextureSet(){const e=new pa({id:yh,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new pa({id:gh,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),s=new pa({id:vh,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),i=new pa({id:Ih,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new pa({id:_h,texture:new Ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=s,this._textures.defaultEmissiveTexture=i,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new ua({id:Th,model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:s,emissiveTexture:i,occlusionTexture:r})}get isPerformanceModel(){return!0}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),p.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Eh),p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),p.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),p.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._setWorldAABBDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),p.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),p.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),p.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0}_setLocalAABBDirty(){for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,s=new Uint8Array(t.length);for(let e=0,i=t.length;e{l.setImage(h,{minFilter:s,magFilter:i,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},h.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 pa({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 s,i,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(s=this._textures[e.colorTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(i=this._textures[e.metallicRoughnessTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else i=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 ua({id:t,model:this,colorTexture:s,metallicRoughnessTexture:i,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});this._textureSets[t]=a}createMesh(e){if(void 0===e.id||null===e.id)return void this.error("[createMesh] SceneModel.createMesh() config missing: id");if(this._scheduledMeshes[e.id])return void this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`);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 void this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`);if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),null;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),null;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'"),null;const t=!!this._dtxEnabled&&("triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive);if(e.origin=e.origin?p.addVec3(this._origin,e.origin,p.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||ph,s=e.position||dh,i=e.rotation||fh;p.eulerToQuaternion(i,"XYZ",mh),e.meshMatrix=p.composeMat4(s,mh,t,p.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Jr(e.positionsDecodeBoundary,p.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])]):Rh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=p.vec3(),s=[];w(e.positions,s,t)&&(e.positions=s,e.origin=p.addVec3(e.origin,t,t))}if(e.positions){const t=p.collapseAABB3();e.positionsDecodeMatrix=p.mat4(),p.expandAABB3Points3(t,e.positions),e.positionsCompressed=qr(e.positions,t,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ut(e.positions,e.indices,null,2):e.edgeIndices=ut(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=Dh(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];w(e.positions,t,uh)&&(e.positions=t,e.origin=p.addVec3(e.origin,uh,p.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=ut(e.positions,e.indices,null,2):e.edgeIndices=ut(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return void this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`)}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return void this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)");if(e.geometry=this._geometries[e.geometryId],!e.geometry)return void this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`);if(e.origin=e.origin?p.addVec3(this._origin,e.origin,p.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.matrix)e.meshMatrix=e.matrix.slice();else{const t=e.scale||ph,s=e.position||dh,i=e.rotation||fh;p.eulerToQuaternion(i,"XYZ",mh),e.meshMatrix=p.composeMat4(s,mh,t,p.mat4())}if(!!this._dtxEnabled&&("triangles"===e.geometry.primitive||"solid"===e.geometry.primitive||"surface"===e.geometry.primitive)){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])]):Rh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=Dh(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):Rh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId]),function(e){if(e.obb=p.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){const t=p.collapseAABB3();p.expandAABB3Points3(t,e.positionsCompressed),gt.decompressAABB(t,e.positionsDecodeMatrix),p.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){const t=p.collapseAABB3();p.expandAABB3Points3(t,e.positions),p.AABB3ToOBB3(t,e.obb)}}(e.geometry)}e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createMesh(e){const t=new ur(this,e.id,e.color,e.opacity);t.pickId=this.scene._renderer.getPickID(t);const s=t.pickId,i=s>>24&255,r=s>>16&255,o=s>>8&255,n=255&s;switch(e.pickColor=new Uint8Array([n,o,r,i]),e.worldAABB=p.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=p.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e);break;case 1:t.layer=this._getVBOBatchingLayer(e);break;case 0:t.layer=this._getVBOInstancingLayer(e)}t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.numPrimitives=e.numPrimitives,p.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t,this._meshList.push(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 s=0,i=e.buckets.length;s>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,s=e.origin,i=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${i}.${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 gn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!1});break;case"solid":n=new gn({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0,solid:!0});break;case"lines":n=new Ln({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0});break;case"points":n=new Aa({model:t,textureSet:a,geometry:l,origin:s,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=p.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=p.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=M),this._pickable&&!1!==e.pickable&&(t|=L),this._culled&&!1!==e.culled&&(t|=F),this._clippable&&!1!==e.clippable&&(t|=U),this._collidable&&!1!==e.collidable&&(t|=H),this._edges&&!1!==e.edges&&(t|=j),this._xrayed&&!1!==e.xrayed&&(t|=G),this._highlighted&&!1!==e.highlighted&&(t|=V),this._selected&&!1!==e.selected&&(t|=k),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];const s=p.collapseAABB3();for(let i=0,r=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,s=this.layerList.length;t0)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 s=0,i=t.visibleLayers.length;s65536?16:8)}else n=[{positionsCompressed:i,indices:r,edgeIndices:o}];return n}const bh=p.vec4(),Ch=p.vec4(),Nh=p.vec3(),Oh=p.vec3(),Sh=p.vec3(),xh=p.vec4(),wh=p.vec4(),Bh=p.vec4();class Mh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,s){let i=!1;const r=this._scene.camera;if(e){const t=p.subVec3(e,r.eye,Nh);i=p.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=p.vec3();p.decomposeMat4(p.inverseMat4(this._scene.viewer.camera.viewMatrix,p.mat4()),t,p.vec4(),p.vec3());const s=p.distVec3(t,e);let i=Math.tan(Math.PI/500)*s*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(i/=this._scene.camera.ortho.scale/2),x(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Di(this._scene,ii({radius:i})),this._pivotSphere=new ei(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){p.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,p.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const s=t.boundary,i=s[2],r=s[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*i/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&&(x(this.getPivotPos(),this._rtcCenter,this._rtcPos),p.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 bt(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=p.lookAtMat4v(e.eye,e.look,e.worldUp);p.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const s=this.getPivotPos();this._cameraOffset[2]+=p.distVec3(e.eye,s),t=p.inverseMat4(t);const i=p.transformVec3(t,this._cameraOffset),r=p.vec3();if(p.subVec3(e.eye,s,r),p.addVec3(r,i),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=p.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=p.normalizeVec3(p.subVec3(e.look,e.eye,Fh)),s=p.cross3Vec3(t,e.worldUp,Lh);return p.sqLenVec3(s)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,s=Math.abs(p.distVec3(this._scene.center,t.eye)),i=t.project.transposedMatrix,r=i.subarray(8,12),o=i.subarray(12),n=[0,0,-1,1],a=p.dotVec4(n,r)/p.dotVec4(n,o),l=Hh;t.project.unproject(e,a,Gh,Vh,l);const h=p.normalizeVec3(p.subVec3(l,t.eye,Fh)),c=p.addVec3(t.eye,p.mulVec3Scalar(h,s,Lh),Uh);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const s=this._scene.camera;var i=-e;const r=-t;1===s.worldUp[2]&&(i=-i),this._azimuth+=.01*-i,this._polar+=.01*r,this._polar=p.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===s.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=p.lenVec3(p.subVec3(s.look,s.eye,p.vec3())),a=this.getPivotPos();p.addVec3(o,a);let l=p.lookAtMat4v(o,a,s.worldUp);l=p.inverseMat4(l);const h=p.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];s.eye=[l[12],l[13],l[14]],p.subVec3(s.eye,p.mulVec3Scalar(c,n),s.look),s.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 jh{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=p.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.snapPick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&e.snappedWorldPos?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents=!0):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,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._needFireEvents=!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=!0):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,cursorPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new ue;e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.snappedWorldPos,e.cursorPos=this.pickCursorPos,e.canvasPos=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=!1}}destroy(){}}const Qh=p.vec2();class Wh{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController;let n,a,l,h=0,c=0,A=0,u=0,d=!1;const f=p.vec3();let m=!0;const E=this._scene.canvas.canvas,y=[];function g(e=!0){E.style.cursor="move",h=i.pointerCanvasPos[0],c=i.pointerCanvasPos[1],A=i.pointerCanvasPos[0],u=i.pointerCanvasPos[1],e&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(d=!0,f.set(o.pickResult.worldPos)):d=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const i=t.keyCode;y[i]=!1}),E.addEventListener("mousedown",this._mouseDownHandler=t=>{if(s.active&&s.pointerEnabled)switch(t.which){case 1:y[e.input.KEY_SHIFT]||s.planView?(n=!0,g()):(n=!0,g(!1));break;case 2:a=!0,g();break;case 3:l=!0,s.panRightClick&&g()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!s.active||!s.pointerEnabled)return;if(!n&&!a&&!l)return;const t=e.canvas.boundary,o=t[2],A=t[3],u=i.pointerCanvasPos[0],m=i.pointerCanvasPos[1];if(y[e.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l){const t=u-h,s=m-c,i=e.camera;if("perspective"===i.projection){const o=Math.abs(d?p.lenVec3(p.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/A,r.panDeltaY+=1.5*s*o/A}else r.panDeltaX+=.5*i.ortho.scale*(t/A),r.panDeltaY+=.5*i.ortho.scale*(s/A)}else!n||a||l||s.planView||(s.firstPerson?(r.rotateDeltaY-=(u-h)/o*s.dragRotationRate/2,r.rotateDeltaX+=(m-c)/A*(s.dragRotationRate/4)):(r.rotateDeltaY-=(u-h)/o*(1.5*s.dragRotationRate),r.rotateDeltaX+=(m-c)/A*(1.5*s.dragRotationRate)));h=u,c=m}),E.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{s.active&&s.pointerEnabled&&i.mouseover&&(m=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),E.addEventListener("mouseup",this._mouseUpHandler=e=>{if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){let s=e.target,i=0,r=0,o=0,n=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,o+=s.scrollLeft,n+=s.scrollTop,s=s.offsetParent;t[0]=e.pageX+o-i,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Qh);const s=Qh[0],i=Qh[1];Math.abs(s-A)<3&&Math.abs(i-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Qh,event:e},!0)}E.style.removeProperty("cursor")}}),E.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.active&&s.pointerEnabled});const v=1/60;let I=null;E.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==I?t-I:0;I=t,o>.05&&(o=.05),o{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),h=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),A=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||h||c||A))return;const u=e.aabb,d=p.getAABB3Diag(u);p.getAABB3Center(u,zh);const f=Math.abs(d/Math.tan(t.cameraFlight.fitFOV*p.DEGTORAD)),m=1.1*d;qh.orthoScale=m,n?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldRight,f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):a?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldForward,f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):l?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldRight,-f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):h?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldForward,-f,Kh),Zh)),qh.look.set(zh),qh.up.set(o.worldUp)):c?(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldUp,f,Kh),Zh)),qh.look.set(zh),qh.up.set(p.normalizeVec3(p.mulVec3Scalar(o.worldForward,1,Yh),Xh))):A&&(qh.eye.set(p.addVec3(zh,p.mulVec3Scalar(o.worldUp,-f,Kh),Zh)),qh.look.set(zh),qh.up.set(p.normalizeVec3(p.mulVec3Scalar(o.worldForward,-1,Yh)))),!s.firstPerson&&s.followPointer&&t.pivotController.setPivotPos(zh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(qh,(()=>{t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(qh),t.pivotController.getPivoting()&&s.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class $h{constructor(e,t,s,i,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,h=!1;const c=this._scene.canvas.canvas,A=s=>{let i;s&&s.worldPos&&(i=s.worldPos);const r=s&&s.entity?s.entity.aabb:e.aabb;if(i){const s=e.camera;p.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(l||h)return;const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),A=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||A||u||p)if(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(h=!0);if(1===t.which&&s.active&&s.pointerEnabled&&(i.mouseDownClientX=t.clientX,i.mouseDownClientY=t.clientY,i.mouseDownCursorX=i.pointerCanvasPos[0],i.mouseDownCursorY=i.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(h=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!s.active||!s.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-i.mouseDownClientX)>3||Math.abs(r.clientY-i.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),h=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),d=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||u||d||f))return(l||h||c)&&(o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!s.firstPerson&&s.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:i.pointerCanvasPos},!0),this._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=i.pointerCanvasPos,o.schedulePickEntity=s.doublePickFlyTo||u||d,o.schedulePickSurface=o.schedulePickEntity&&d,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),s.doublePickFlyTo&&(A(o.pickResult),!s.firstPerson&&s.followPointer)){const e=o.pickResult.entity.aabb,s=p.getAABB3Center(e);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:i.pointerCanvasPos},!0),s.doublePickFlyTo&&(A(),!s.firstPerson&&s.followPointer)){const s=e.aabb,i=p.getAABB3Center(s);t.pivotController.setPivotPos(i),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 ec{constructor(e,t,s,i,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=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&i.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(i=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&(n[i]=!1,i===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!i.mouseover)return;const h=t.cameraControl,c=a.deltaTime/1e3;if(!s.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,n),i=h._isKeyDownForAction(h.ROTATE_Y_NEG,n),o=h._isKeyDownForAction(h.ROTATE_X_POS,n),a=h._isKeyDownForAction(h.ROTATE_X_NEG,n),l=c*s.keyboardRotationRate;(e||i||o||a)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:i&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!s.firstPerson&&s.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,n),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,n);if(e||o){const n=c*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(i.followPointerDirty=!0,l=!1)}}const A=h._isKeyDownForAction(h.PAN_FORWARDS,n),u=h._isKeyDownForAction(h.PAN_BACKWARDS,n),p=h._isKeyDownForAction(h.PAN_LEFT,n),d=h._isKeyDownForAction(h.PAN_RIGHT,n),f=h._isKeyDownForAction(h.PAN_UP,n),m=h._isKeyDownForAction(h.PAN_DOWN,n),E=(n[o.KEY_ALT]?.3:1)*c*s.keyboardPanRate;(A||u||p||d||f||m)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=E:f&&(r.panDeltaY+=-E),d?r.panDeltaX+=-E:p&&(r.panDeltaX+=E),u?r.panDeltaZ+=E:A&&(r.panDeltaZ+=-E))}))}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 tc=.001,sc=p.vec3();class ic{constructor(e,t,s,i,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let h=1,c=1,A=null;this._onTick=e.on("tick",(()=>{if(!s.active||!s.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta){i.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{i.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{oc(e,o,i.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{s.active&&s.pointerEnabled&&(oc(e,o,i.pointerCanvasPos),i.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{s.active&&s.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 oc(e,t,s){if(e){const{x:i,y:r}=t.getBoundingClientRect();s[0]=e.clientX-i,s[1]=e.clientY-r}else e=window.event,s[0]=e.x,s[1]=e.y;return s}const nc=function(e,t){if(e){let s=e.target,i=0,r=0;for(;s.offsetParent;)i+=s.offsetLeft,r+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-i,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class ac{constructor(e,t,s,i,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=p.vec2(),l=p.vec2(),h=p.vec2(),c=p.vec2(),A=[],u=this._scene.canvas.canvas;let d=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!s.active||!s.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(i.touchStartTime=Date.now(),1===r.length&&1===l.length&&(nc(r[0],a),s.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),s.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!s.firstPerson&&n.startPivot()&&n.showPivot()):(s.smartPivot?n.setCanvasPivotPos(i.pointerCanvasPos):n.setPivotPos(e.camera.look),!s.firstPerson&&n.startPivot()&&n.showPivot()))));A.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],m=t.touches;if(t.touches.length===d){if(1===d){nc(m[0],l),p.subVec2(l,A[0],c);const t=c[0],o=c[1];if(null!==i.longTouchTimeout&&(Math.abs(t)>s.longTapRadius||Math.abs(o)>s.longTapRadius)&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),s.planView){const i=e.camera;if("perspective"===i.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(i.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*s.touchPanRate,r.panDeltaY+=o*n/u*s.touchPanRate}else r.panDeltaX+=.5*i.ortho.scale*(t/u)*s.touchPanRate,r.panDeltaY+=.5*i.ortho.scale*(o/u)*s.touchPanRate}else r.rotateDeltaY-=t/a*(1*s.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*s.dragRotationRate)}else if(2===d){const t=m[0],n=m[1];nc(t,l),nc(n,h);const a=p.geometricMeanVec2(A[0],A[1]),c=p.geometricMeanVec2(l,h),d=p.vec2();p.subVec2(a,c,d);const f=d[0],E=d[1],y=e.camera,g=p.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),v=(p.distVec2(A[0],A[1])-g)*s.touchDollyRate;if(r.dollyDelta=v,Math.abs(v)<1)if("perspective"===y.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,i=Math.abs(p.lenVec3(p.subVec3(t,e.camera.eye,[])))*Math.tan(y.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*i/u*s.touchPanRate,r.panDeltaY-=E*i/u*s.touchPanRate}else r.panDeltaX-=.5*y.ortho.scale*(f/u)*s.touchPanRate,r.panDeltaY-=.5*y.ortho.scale*(E/u)*s.touchPanRate;i.pointerCanvasPos=c}for(let e=0;e{let i;s&&s.worldPos&&(i=s.worldPos);const r=s?s.entity.aabb:e.aabb;if(i){const s=e.camera;p.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!s.active||!s.pointerEnabled)return;null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,lc(r[0],h);const o=h[0],n=h[1],l=r[0].pageX,A=r[0].pageY;i.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(A)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),i.longTouchTimeout=null}),s.longTapTimeout)}else c=-1;for(;l.length{if(!s.active||!s.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==i.longTouchTimeout&&(clearTimeout(i.longTouchTimeout),i.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(A>-1&&c-A<325?(lc(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),s.doublePickFlyTo&&d(o.pickResult)):(n.fire("doublePickedNothing"),s.doublePickFlyTo&&d()),A=-1):p.distVec2(l[0],h)<4&&(lc(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"),A=t),c=-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:p.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:p.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const s=this.scene;this._controllers={cameraControl:this,pickController:new jh(this,this._configs),pivotController:new kh(s,this._configs),panController:new Mh(s),cameraFlight:new lr(this,{duration:.5})},this._handlers=[new rc(this.scene,this._controllers,this._configs,this._states,this._updates),new ac(this.scene,this._controllers,this._configs,this._states,this._updates),new Wh(this.scene,this._controllers,this._configs,this._states,this._updates),new Jh(this.scene,this._controllers,this._configs,this._states,this._updates),new $h(this.scene,this._controllers,this._configs,this._states,this._updates),new hc(this.scene,this._controllers,this._configs,this._states,this._updates),new ec(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new ic(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,s={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":s[this.PAN_LEFT]=[t.KEY_A],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_Z],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":s[this.PAN_LEFT]=[t.KEY_Q],s[this.PAN_RIGHT]=[t.KEY_D],s[this.PAN_UP]=[t.KEY_W],s[this.PAN_DOWN]=[t.KEY_X],s[this.PAN_BACKWARDS]=[],s[this.PAN_FORWARDS]=[],s[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],s[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],s[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],s[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],s[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],s[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],s[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],s[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],s[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],s[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],s[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],s[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=s}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const s=this._keyMap[e];if(!s)return!1;t||(t=this.scene.input.keyDown);for(let e=0,i=s.length;e0?mc(t):null,n=s&&s.length>0?mc(s):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&i.push(e.id);const s=e.children;if(s)for(var r=0,l=s.length;r * Copyright (c) 2022 Niklas von Hertzen diff --git a/dist/xeokit-bim-viewer.umd.js b/dist/xeokit-bim-viewer.umd.js index 268d570d..13f172c7 100644 --- a/dist/xeokit-bim-viewer.umd.js +++ b/dist/xeokit-bim-viewer.umd.js @@ -55593,7 +55593,7 @@ */ constructor(cfg) { - console.info("Creating TrianglesInstancingLayer"); + // console.info("Creating TrianglesInstancingLayer"); /** * Owner model @@ -74431,7 +74431,7 @@ return dtxLayer; } } - console.info(`[SceneModel ${this.id}]: creating TrianglesDataTextureLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesDataTextureLayer`); dtxLayer = new TrianglesDataTextureLayer(this, {layerIndex: 0, origin}); // layerIndex is set in #finalize() this._dtxLayers[layerId] = dtxLayer; this.layerList.push(dtxLayer); @@ -74454,7 +74454,7 @@ while (!vboBatchingLayer) { switch (cfg.primitive) { case "triangles": - console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); vboBatchingLayer = new TrianglesBatchingLayer({ model, textureSet, @@ -74469,7 +74469,7 @@ }); break; case "solid": - console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); vboBatchingLayer = new TrianglesBatchingLayer({ model, textureSet, @@ -74484,7 +74484,7 @@ }); break; case "surface": - console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`); vboBatchingLayer = new TrianglesBatchingLayer({ model, textureSet, @@ -74499,7 +74499,7 @@ }); break; case "lines": - console.info(`[SceneModel ${this.id}]: creating LinesBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating LinesBatchingLayer`); vboBatchingLayer = new LinesBatchingLayer({ model, layerIndex: 0, // This is set in #finalize() @@ -74511,7 +74511,7 @@ }); break; case "points": - console.info(`[SceneModel ${this.id}]: creating PointsBatchingLayer`); + // console.info(`[SceneModel ${this.id}]: creating PointsBatchingLayer`); vboBatchingLayer = new PointsBatchingLayer({ model, layerIndex: 0, // This is set in #finalize() @@ -74565,7 +74565,7 @@ while (!vboInstancingLayer) { switch (geometry.primitive) { case "triangles": - console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer = new TrianglesInstancingLayer({ model, textureSet, @@ -74576,7 +74576,7 @@ }); break; case "solid": - console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer = new TrianglesInstancingLayer({ model, textureSet, @@ -74587,7 +74587,7 @@ }); break; case "surface": - console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer = new TrianglesInstancingLayer({ model, textureSet, @@ -74598,7 +74598,7 @@ }); break; case "lines": - console.info(`[SceneModel ${this.id}]: creating LinesInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating LinesInstancingLayer`); vboInstancingLayer = new LinesInstancingLayer({ model, textureSet, @@ -74608,7 +74608,7 @@ }); break; case "points": - console.info(`[SceneModel ${this.id}]: creating PointsInstancingLayer`); + // console.info(`[SceneModel ${this.id}]: creating PointsInstancingLayer`); vboInstancingLayer = new PointsInstancingLayer({ model, textureSet,