@xeokit/xeokit-sdk 2.4.2-beta-8 → 2.4.2-beta-9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/xeokit-sdk.cjs.js +47 -18
- package/dist/xeokit-sdk.es.js +47 -18
- package/dist/xeokit-sdk.es5.js +75 -66
- package/dist/xeokit-sdk.min.cjs.js +1 -1
- package/dist/xeokit-sdk.min.es.js +1 -1
- package/dist/xeokit-sdk.min.es5.js +1 -1
- package/package.json +1 -1
- package/src/viewer/metadata/MetaModel.js +17 -2
- package/src/viewer/scene/model/vbo/linesInstancing/LinesInstancingLayer.js +5 -0
- package/src/viewer/scene/model/vbo/pointsInstancing/PointsInstancingLayer.js +4 -0
- package/src/viewer/scene/model/vbo/trianglesInstancing/TrianglesInstancingLayer.js +21 -16
- package/types/viewer/scene/mesh/Mesh.d.ts +7 -0
- package/types/viewer/scene/models/PerformanceModel/PerformanceModel.d.ts +3 -609
- package/types/viewer/scene/models/SceneModel.d.ts +708 -0
- package/types/viewer/scene/models/SceneModelEntity.d.ts +418 -0
- package/types/viewer/scene/models/SceneModelMesh.d.ts +68 -0
- package/types/viewer/scene/models/SceneModelTexture.d.ts +16 -0
- package/types/viewer/scene/models/SceneModelTextureSet.d.ts +51 -0
- package/types/viewer/scene/models/SceneModelTransform.d.ts +197 -0
- package/types/viewer/scene/models/VBOSceneModel/VBOSceneModel.d.ts +2 -610
- package/types/viewer/scene/models/index.d.ts +8 -1
|
@@ -14,7 +14,7 @@ class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){
|
|
|
14
14
|
/**
|
|
15
15
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
16
16
|
* @license MIT
|
|
17
|
-
**/let mc=null;function vc(e,t){const s=3*e,n=3*t;let i,a,r,l,o,c;const u=Math.min(i=mc[s],a=mc[s+1],r=mc[s+2]),h=Math.min(l=mc[n],o=mc[n+1],c=mc[n+2]);if(u!==h)return u-h;const p=Math.max(i,a,r),A=Math.max(l,o,c);return p!==A?p-A:0}let wc=null;function gc(e,t){let s=wc[2*e]-wc[2*t];return 0!==s?s:wc[2*e+1]-wc[2*t+1]}function Ec(e,t,s=!1){const n=e.positionsCompressed||[],i=function(e,t){const s=new Int32Array(e.length/3);for(let e=0,t=s.length;e<t;e++)s[e]=e;mc=new Int32Array(e.length);for(let s=0,n=e.length;s<n;s++)mc[s]=e[s]>>t;s.sort(vc);const n=new Int32Array(e.length);for(let t=0,i=s.length;t<i;t++)n[3*t+0]=e[3*s[t]+0],n[3*t+1]=e[3*s[t]+1],n[3*t+2]=e[3*s[t]+2];return n}(e.indices||[],t),a=function(e){if(0===(e||[]).length)return[];let t=new Int32Array(e.length/2);for(let e=0,s=t.length;e<s;e++)t[e]=e;for(let t=0,s=e.length;t<s;t+=2)if(e[t]>e[t+1]){let s=e[t];e[t]=e[t+1],e[t+1]=s}wc=new Int32Array(e),t.sort(gc);const s=new Int32Array(e.length);for(let n=0,i=t.length;n<i;n++)s[2*n+0]=e[2*t[n]+0],s[2*n+1]=e[2*t[n]+1];return s}(e.edgeIndices||[]);function r(e,t){if(e>t){let s=e;e=t,t=s}function s(s,n){return s!==e?e-s:n!==t?t-n:0}let n=0,i=(a.length>>1)-1;for(;n<=i;){const e=i+n>>1,t=s(a[2*e],a[2*e+1]);if(t>0)n=e+1;else{if(!(t<0))return e;i=e-1}}return-n-1}const l=new Int32Array(a.length/2);l.fill(0);const o=n.length/3;if(o>8*(1<<t))return[e];const c=new Int32Array(o);c.fill(-1);const u=[];function h(){c.fill(-1);const e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:u.length};return u.push(e),e}let p=h();for(let t=0,s=i.length;t<s;t+=3){let s=0;const o=i[t],u=i[t+1],A=i[t+2];if(-1===c[o]&&s++,-1===c[u]&&s++,-1===c[A]&&s++,s+p.numPositions>p.maxNumPositions&&(p=h()),p.bucketNumber>8)return[e];let d;-1===c[o]&&(c[o]=p.numPositions++,p.positionsCompressed.push(n[3*o]),p.positionsCompressed.push(n[3*o+1]),p.positionsCompressed.push(n[3*o+2])),-1===c[u]&&(c[u]=p.numPositions++,p.positionsCompressed.push(n[3*u]),p.positionsCompressed.push(n[3*u+1]),p.positionsCompressed.push(n[3*u+2])),-1===c[A]&&(c[A]=p.numPositions++,p.positionsCompressed.push(n[3*A]),p.positionsCompressed.push(n[3*A+1]),p.positionsCompressed.push(n[3*A+2])),p.indices.push(c[o]),p.indices.push(c[u]),p.indices.push(c[A]),(d=r(o,u))>=0&&0===l[d]&&(l[d]=1,p.edgeIndices.push(c[a[2*d]]),p.edgeIndices.push(c[a[2*d+1]])),(d=r(o,A))>=0&&0===l[d]&&(l[d]=1,p.edgeIndices.push(c[a[2*d]]),p.edgeIndices.push(c[a[2*d+1]])),(d=r(u,A))>=0&&0===l[d]&&(l[d]=1,p.edgeIndices.push(c[a[2*d]]),p.edgeIndices.push(c[a[2*d+1]]))}const A=t/8*2,d=t/8,f=2*n.length+(i.length+a.length)*A;let I=0,y=-n.length/3;return u.forEach((e=>{I+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*d,y+=e.positionsCompressed.length/3})),I>f?[e]:(s&&function(e,t){const s={},n={};let i=0;e.forEach((e=>{const t=e.indices,a=e.edgeIndices,r=e.positionsCompressed;for(let e=0,n=t.length;e<n;e+=3){const n=r[3*t[e]]+"_"+r[3*t[e]+1]+"_"+r[3*t[e]+2]+"/"+r[3*t[e+1]]+"_"+r[3*t[e+1]+1]+"_"+r[3*t[e+1]+2]+"/"+r[3*t[e+2]]+"_"+r[3*t[e+2]+1]+"_"+r[3*t[e+2]+2];s[n]=!0}i+=e.edgeIndices.length/2;for(let e=0,t=a.length;e<t;e+=2){const t=r[3*a[e]]+"_"+r[3*a[e]+1]+"_"+r[3*a[e]+2]+"/"+r[3*a[e+1]]+"_"+r[3*a[e+1]+1]+"_"+r[3*a[e+1]+2]+"/";n[t]=!0}}));{const e=t.indices;t.edgeIndices;const n=t.positionsCompressed;for(let t=0,i=e.length;t<i;t+=3){const i=n[3*e[t]]+"_"+n[3*e[t]+1]+"_"+n[3*e[t]+2]+"/"+n[3*e[t+1]]+"_"+n[3*e[t+1]+1]+"_"+n[3*e[t+1]+2]+"/"+n[3*e[t+2]]+"_"+n[3*e[t+2]+1]+"_"+n[3*e[t+2]+2];if(!(i in s))throw console.log("Not found "+i),"Ohhhh!"}}}(u,e),u)}const Tc=d.vec3(),bc=d.vec3(),Dc=d.vec3(),Pc=d.vec3(),Rc=d.vec4(),Cc=d.mat4();class _c{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a;if(!this._program&&(this._allocate(),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Tc;if(I){const t=d.transformPoint3(h,c,bc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(i.viewMatrix,e,Cc),f=Dc,f[0]=i.eye[0]-e[0],f[1]=i.eye[1]-e[1],f[2]=i.eye[2]-e[2]}else A=i.viewMatrix,f=i.eye;if(r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const m=n._sectionPlanesState.sectionPlanes.length;if(m>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,i=a.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Pc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Pe(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uLightAmbient=n.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const i=s.lights;let a;for(let e=0,t=i.length;e<t;e++)switch(a=i[e],a.type){case"dir":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=n.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=n.getLocation("lightDir"+e),this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e)}this._uSceneModelMatrix=n.getLocation("sceneModelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState.lights,a=t.camera.project;n.bind(),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=i.length;e<t;e++){const t=i[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const n=t.sao;if(n.possible){const t=s.drawingBufferWidth,i=s.drawingBufferHeight;Rc[0]=t,Rc[1]=i,Rc[2]=n.blendCutoff,Rc[3]=n.blendFactor,s.uniform4fv(this._uSAOParams,Rc),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// TrianglesDataTextureColorRenderer vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),a.push("uniform mat4 sceneModelMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),a.push("uniform highp sampler2D uTexturePerObjectMatrix;"),a.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),a.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),a.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),a.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),a.push("uniform vec3 uCameraEyeRtc;"),a.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("out float isPerspective;")),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++)i=s.lights[e],"ambient"!==i.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));n&&(a.push("out vec4 vWorldPosition;"),a.push("flat out uint vFlags2;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int polygonIndex = gl_VertexID / 3;"),a.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),a.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),a.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),a.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),a.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),a.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),a.push("if (int(flags.x) != renderPass) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("} else {"),a.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),a.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),a.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),a.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),a.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),a.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),a.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),a.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),a.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),a.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),a.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),a.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),a.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),a.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),a.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),a.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),a.push("if (color.a == 0u) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("};"),a.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),a.push("vec3 position;"),a.push("position = positions[gl_VertexID % 3];"),a.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),a.push("if (solid != 1u) {"),a.push("if (isPerspectiveMatrix(projMatrix)) {"),a.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),a.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("} else {"),a.push("if (viewNormal.z < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("}"),a.push("}"),a.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),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;");for(let e=0,t=s.lights.length;e<t;e++)if(i=s.lights[e],"ambient"!==i.type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = vec3(color.rgb) / 255.0;"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags2 = flags2.r;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// TrianglesDataTextureColorRenderer 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("}")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Bc=new Float32Array([1,1,1]),Oc=d.vec3(),Sc=d.vec3(),Nc=d.vec3(),xc=d.vec3(),Lc=d.mat4();class Mc{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a,A=i.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,I;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==u[0]||0!==u[1]||0!==u[2]){const e=Oc;if(c){const t=Sc;d.transformPoint3(h,c,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]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,Lc),I=Nc,I[0]=i.eye[0]-e[0],I[1]=i.eye[1]-e[1],I[2]=i.eye[2]-e[2]}else f=A,I=i.eye;if(r.uniform3fv(this._uCameraEyeRtc,I),r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uWorldMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),s===sr.SILHOUETTE_XRAYED){const e=n.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.SILHOUETTE_HIGHLIGHTED){const e=n.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.SILHOUETTE_SELECTED){const e=n.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else r.uniform4fv(this._uColor,Bc);if(n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const y=n._sectionPlanesState.sectionPlanes.length;if(y>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,i=a.renderFlags;for(let t=0;t<y;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,xc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Triangles dataTexture 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = color;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Fc=new Float32Array([0,0,0,1]),Hc=d.vec3(),Uc=d.vec3(),Gc=d.vec3(),jc=d.mat4();class Vc{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=a.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Hc;if(I){const t=d.transformPoint3(h,c,Uc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,jc)}else f=A;if(r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),s===sr.EDGES_XRAYED){const e=i.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.EDGES_HIGHLIGHTED){const e=i.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.EDGES_SELECTED){const e=i.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else r.uniform4fv(this._uColor,Fc);const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Gc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(r.LINES,0,l.numEdgeIndices8Bits)),l.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(r.LINES,0,l.numEdgeIndices16Bits)),l.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(r.LINES,0,l.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,n=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&n.push("#extension GL_EXT_frag_depth : enable"),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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vColor;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const kc=d.vec3(),Qc=d.vec3(),Wc=d.vec3(),zc=d.mat4();class Kc{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=a.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=kc;if(I){const t=d.transformPoint3(h,c,Qc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,zc)}else f=A;r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Wc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(r.LINES,0,l.numEdgeIndices8Bits)),l.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(r.LINES,0,l.numEdgeIndices16Bits)),l.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(r.LINES,0,l.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,n=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// 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 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform highp sampler2D uObjectPerObjectOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// TrianglesDataTextureEdgesColorRenderer"),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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vColor;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yc=d.vec3(),Xc=d.vec3(),qc=d.vec3(),Jc=d.mat4();class Zc{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n;let A,f;o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Yc;if(I){const t=d.transformPoint3(h,c,Xc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(a.viewMatrix,e,Jc),f=qc,f[0]=a.eye[0]-e[0],f[1]=a.eye[1]-e[1],f[2]=a.eye[2]-e[2]}else A=a.viewMatrix,f=a.eye;if(r.uniform2fv(this._uPickClipPos,e.pickClipPos),r.uniform2f(this._uDrawingBufferSize,r.drawingBufferWidth,r.drawingBufferHeight),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.project.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,e)}const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Yc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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*objectDecodeAndInstanceMatrix)) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uvec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outPickColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (float(vFlags2.x) > 0.0);"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outPickColor = vPickColor; "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $c=d.vec3(),eu=d.vec3(),tu=d.vec3(),su=d.vec3(),nu=d.mat4();class iu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=e.pickViewMatrix||a.viewMatrix;let f,I;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==u[0]||0!==u[1]||0!==u[2]){const t=$c;if(c){const e=eu;d.transformPoint3(h,c,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]+=u[0],t[1]+=u[1],t[2]+=u[2],f=N(A,t,nu),I=tu,I[0]=a.eye[0]-t[0],I[1]=a.eye[1]-t[1],I[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=A,I=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(r.uniform3fv(this._uCameraEyeRtc,I),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniform2fv(this._uPickClipPos,e.pickClipPos),r.uniform2f(this._uDrawingBufferSize,r.drawingBufferWidth,r.drawingBufferHeight),r.uniform1f(this._uPickZNear,e.pickZNear),r.uniform1f(this._uPickZFar,e.pickZFar),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,a=n.renderFlags;for(let t=0;t<y;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,su);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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*objectDecodeAndInstanceMatrix)) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Triangles dataTexture pick depth 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 float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outPackedDepth;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outPackedDepth = packDepth(zNormalizedDepth); "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const au=d.vec3(),ru=d.vec3(),lu=d.vec3(),ou=d.vec3(),cu=d.vec3(),uu=d.mat4();class hu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=t.aabb,f=e.pickViewMatrix||a.viewMatrix,I=au;let y,m;I[0]=d.safeInv(A[3]-A[0])*d.MAX_INT,I[1]=d.safeInv(A[4]-A[1])*d.MAX_INT,I[2]=d.safeInv(A[5]-A[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(I[0]),e.snapPickCoordinateScale[1]=d.safeInv(I[1]),e.snapPickCoordinateScale[2]=d.safeInv(I[2]),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==c[0]||0!==c[1]||0!==c[2],w=0!==u[0]||0!==u[1]||0!==u[2];if(v||w){const t=ru;if(v){const e=d.transformPoint3(h,c,lu);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=u[0],t[1]+=u[1],t[2]+=u[2],y=N(f,t,uu),m=ou,m[0]=a.eye[0]-t[0],m[1]=a.eye[1]-t[1],m[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else y=f,m=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,m),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,I),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,y),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const g=i._sectionPlanesState.sectionPlanes.length;if(g>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*g,a=n.renderFlags;for(let t=0;t<g;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,cu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}const E="edge"===e.snapMode?r.LINES:r.POINTS;l.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(E,0,l.numEdgeIndices8Bits)),l.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(E,0,l.numEdgeIndices16Bits)),l.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(E,0,l.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=s.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("uSnapVectorA"),this.uInverseVectorAB=s.getLocation("uSnapInvVectorAB"),this._uLayerNumber=s.getLocation("uLayerNumber"),this._uCoordinateScaler=s.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=e.sectionPlanes.length;t<n;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("out highp ivec4 outCoords;"),s.push("void main(void) {"),t){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 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 pu=d.vec3(),Au=d.vec3(),du=d.vec3(),fu=d.vec3(),Iu=d.vec3(),yu=d.mat4();class mu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=t.aabb,f=e.pickViewMatrix||a.viewMatrix,I=pu;let y,m;I[0]=d.safeInv(A[3]-A[0])*d.MAX_INT,I[1]=d.safeInv(A[4]-A[1])*d.MAX_INT,I[2]=d.safeInv(A[5]-A[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(I[0]),e.snapPickCoordinateScale[1]=d.safeInv(I[1]),e.snapPickCoordinateScale[2]=d.safeInv(I[2]),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==c[0]||0!==c[1]||0!==c[2],w=0!==u[0]||0!==u[1]||0!==u[2];if(v||w){const t=Au;if(v){const e=du;d.transformPoint3(h,c,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]+=u[0],t[1]+=u[1],t[2]+=u[2],y=N(f,t,yu),m=fu,m[0]=a.eye[0]-t[0],m[1]=a.eye[1]-t[1],m[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else y=f,m=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,m),r.uniform2fv(this._uVectorA,e.snapVectorA),r.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,I),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,y),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const g=i._sectionPlanesState.sectionPlanes.length;if(g>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*g,a=n.renderFlags;for(let t=0;t<g;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Iu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=s.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this._uVectorA=s.getLocation("uVectorAB"),this._uInverseVectorAB=s.getLocation("uInverseVectorAB"),this._uLayerNumber=s.getLocation("uLayerNumber"),this._uCoordinateScaler=s.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// 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 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vWorldPosition = worldPosition;"),t&&s.push("vFlags2 = flags2.r;"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),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;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("flat in uint vFlags2;");for(let t=0,n=e.sectionPlanes.length;t<n;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("layout(location = 0) out highp ivec4 outCoords;"),s.push("layout(location = 1) out highp ivec4 outNormal;"),s.push("layout(location = 2) out lowp uvec4 outPickColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 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("vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vu=d.vec3(),wu=d.vec3(),gu=d.vec3(),Eu=d.vec3(),Tu=d.mat4();class bu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=e.pickViewMatrix||a.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,I;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==u[0]||0!==u[1]||0!==u[2]){const e=vu;if(c){const t=wu;d.transformPoint3(h,c,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]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,Tu),I=gu,I[0]=a.eye[0]-e[0],I[1]=a.eye[1]-e[1],I[2]=a.eye[2]-e[2]}else f=A,I=a.eye;r.uniform3fv(this._uCameraEyeRtc,I),r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uWorldMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,a=n.renderFlags;for(let t=0;t<y;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Eu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){const e=this._scene;e.canvas.gl,e.camera.project,this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureOcclusionRenderer 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 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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("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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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*objectDecodeAndInstanceMatrix)) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),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("flat in uint vFlags2;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (float(vFlags2) > 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push(" if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Du=d.vec3(),Pu=d.vec3(),Ru=d.vec3(),Cu=d.vec3(),_u=d.mat4();class Bu{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a;if(!this._program&&(this._allocate(),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Du;if(I){const t=d.transformPoint3(h,c,Pu);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(i.viewMatrix,e,_u),f=Ru,f[0]=i.eye[0]-e[0],f[1]=i.eye[1]-e[1],f[2]=i.eye[2]-e[2]}else A=i.viewMatrix,f=i.eye;if(r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const m=n._sectionPlanesState.sectionPlanes.length;if(m>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,i=a.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Cu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t.camera.project;if(n.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState;e._lightsState;const s=t.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture draw vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out highp vec2 vHighPrecisionZW;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2.r;")),n.push("gl_Position = clipPos;"),n.push("vHighPrecisionZW = gl_Position.zw;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles dataTexture 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"),n.push("in highp vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ou=d.vec3(),Su=d.vec3(),Nu=d.vec3(),xu=d.vec3(),Lu=d.mat4();class Mu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:h}=n,p=a.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const I=0!==o[0]||0!==o[1]||0!==o[2],y=0!==c[0]||0!==c[1]||0!==c[2];if(I||y){const e=Ou;if(I){const t=Su;d.transformPoint3(u,o,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],A=N(p,e,Lu),f=Nu,f[0]=a.eye[0]-e[0],f[1]=a.eye[1]-e[1],f[2]=a.eye[2]-e[2]}else A=p,f=a.eye;r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uWorldMatrix,!1,h),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,a.viewNormalMatrix),r.uniformMatrix4fv(this._uWorldNormalMatrix,!1,n.worldNormalMatrix);const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(o){const e=F(s.dist,s.dir,o,xu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.objectDecodeAndInstanceMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aNormal.bindArrayBuffer(l.normalsBuf),this._aColor.bindArrayBuffer(l.colorsBuf),this._aFlags.bindArrayBuffer(l.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(l.flags2Buf),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("objectDecodeAndInstanceMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&ye.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 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),ye.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 * (objectDecodeAndInstanceMatrix * 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&&(ye.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,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&ye.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),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&&ye.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("void main(void) {"),s){n.push(" bool clippable = (float(vFlags2.x) > 0.0);"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&ye.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Fu=d.vec3(),Hu=d.vec3(),Uu=d.vec3(),Gu=d.vec3();d.vec4();const ju=d.mat4();class Vu{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a;if(!this._program&&(this._allocate(),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Fu;if(I){const t=d.transformPoint3(h,c,Hu);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(i.viewMatrix,e,ju),f=Uu,f[0]=i.eye[0]-e[0],f[1]=i.eye[1]-e[1],f[2]=i.eye[2]-e[2]}else A=i.viewMatrix,f=i.eye;if(r.uniform2fv(this._uPickClipPos,e.pickClipPos),r.uniform2f(this._uDrawingBufferSize,r.drawingBufferWidth,r.drawingBufferHeight),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const m=n._sectionPlanesState.sectionPlanes.length;if(m>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,i=a.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Gu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t.camera.project;if(n.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState;e._lightsState;const s=t.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// trianglesDatatextureNormalsRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("uniform vec2 pickClipPos;"),n.push("uniform vec2 drawingBufferSize;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out vec4 vWorldPosition;"),s&&n.push("flat out uint vFlags2;"),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("vWorldPosition = worldPosition;"),s&&n.push("vFlags2 = flags2.r;"),n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// TrianglesDataTexturePickNormalsRenderer 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("in vec4 vWorldPosition;"),s){n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ku{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 Mc(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Zc(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new iu(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Vu(this._scene)),this._vertexDepthRenderer||(this._vertexDepthRenderer=new hu(this._scene)),this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new mu(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _c(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _c(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Mc(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Bu(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Mu(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Vc(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Kc(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zc(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Vu(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Vu(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new iu(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new hu(this._scene)),this._vertexDepthRenderer}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new mu(this._scene)),this._snapDepthBufInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new bu(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 Qu={};class Wu{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class zu{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,s,n,i){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,s,2),this.texturePerObjectColorsAndFlags.bindTexture(e,n,3),this.texturePerObjectInstanceMatrices.bindTexture(e,i,4)}bindTriangleIndicesTextures(e,t,s,n){this.indicesPortionIdsPerBitnessTextures[n].bindTexture(e,t,5),this.indicesPerBitnessTextures[n].bindTexture(e,s,6)}bindEdgeIndicesTextures(e,t,s,n){this.edgeIndicesPortionIdsPerBitnessTextures[n].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[n].bindTexture(e,s,6)}}class Ku{constructor(e,t,s,n,i=null){this._gl=e,this._texture=t,this._textureWidth=s,this._textureHeight=n,this._textureData=i}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 Yu={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(Yu,null,4));let e=0;Object.keys(Yu).forEach((t=>{t.startsWith("size")&&(e+=Yu[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Yu.totalPolygons).toFixed(2)}`);let t={};Object.keys(Yu).forEach((s=>{s.startsWith("size")&&(t[s]=`${(Yu[s]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Xu{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,n,i,a,r){const l=t.length;this.numPortions=l;const o=4096,c=Math.ceil(l/512);if(0===c)throw"texture height===0";const u=new Uint8Array(16384*c);Yu.sizeDataColorsAndFlags+=u.byteLength,Yu.numberOfTextures++;for(let e=0;e<l;e++)u.set(t[e],32*e+0),u.set(s[e],32*e+4),u.set([0,0,0,0],32*e+8),u.set([0,0,0,0],32*e+12),u.set([n[e]>>24&255,n[e]>>16&255,n[e]>>8&255,255&n[e]],32*e+16),u.set([i[e]>>24&255,i[e]>>16&255,i[e]>>8&255,255&i[e]],32*e+20),u.set([a[e]>>24&255,a[e]>>16&255,a[e]>>8&255,255&a[e]],32*e+24),u.set([r[e]?1:0,0,0,0],32*e+28);const h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,c),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,c,e.RGBA_INTEGER,e.UNSIGNED_BYTE,u,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 Ku(e,h,o,c,u)}generateTextureForObjectOffsets(e,t){const s=512,n=Math.ceil(t/s);if(0===n)throw"texture height===0";const i=new Float32Array(1536*n).fill(0);Yu.sizeDataTextureOffsets+=i.byteLength,Yu.numberOfTextures++;const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,s,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,n,e.RGB,e.FLOAT,i,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 Ku(e,a,s,n,i)}generateTextureForInstancingMatrices(e,t){const s=t.length;if(0===s)throw"num instance matrices===0";const n=2048,i=Math.ceil(s/512),a=new Float32Array(8192*i);Yu.numberOfTextures++;for(let e=0;e<t.length;e++)a.set(t[e],16*e);const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGBA,e.FLOAT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i,a)}generateTextureForPositionsDecodeMatrices(e,t){const s=t.length;if(0===s)throw"num decode+entity matrices===0";const n=2048,i=Math.ceil(s/512),a=new Float32Array(8192*i);Yu.sizeDataPositionDecodeMatrices+=a.byteLength,Yu.numberOfTextures++;for(let e=0;e<t.length;e++)a.set(t[e],16*e);const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGBA,e.FLOAT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor8BitIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/3/n);if(0===i)throw"texture height===0";const a=new Uint8Array(n*i*3);Yu.sizeDataTextureIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGB_INTEGER,e.UNSIGNED_BYTE,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor16BitIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/3/n);if(0===i)throw"texture height===0";const a=new Uint16Array(n*i*3);Yu.sizeDataTextureIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGB_INTEGER,e.UNSIGNED_SHORT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor32BitIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/3/n);if(0===i)throw"texture height===0";const a=new Uint32Array(n*i*3);Yu.sizeDataTextureIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGB_INTEGER,e.UNSIGNED_INT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor8BitsEdgeIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/2/n);if(0===i)throw"texture height===0";const a=new Uint8Array(n*i*2);Yu.sizeDataTextureEdgeIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RG_INTEGER,e.UNSIGNED_BYTE,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor16BitsEdgeIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/2/n);if(0===i)throw"texture height===0";const a=new Uint16Array(n*i*2);Yu.sizeDataTextureEdgeIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RG_INTEGER,e.UNSIGNED_SHORT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor32BitsEdgeIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/2/n);if(0===i)throw"texture height===0";const a=new Uint32Array(n*i*2);Yu.sizeDataTextureEdgeIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RG_INTEGER,e.UNSIGNED_INT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureForPositions(e,t,s){const n=s/3,i=4096,a=Math.ceil(n/i);if(0===a)throw"texture height===0";const r=new Uint16Array(i*a*3);Yu.sizeDataTexturePositions+=r.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];r.set(n,s),s+=n.length}const l=e.createTexture();return e.bindTexture(e.TEXTURE_2D,l),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,i,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,a,e.RGB_INTEGER,e.UNSIGNED_SHORT,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 Ku(e,l,i,a)}generateTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const s=t.length,n=4096,i=Math.ceil(s/n);if(0===i)throw"texture height===0";const a=new Uint16Array(n*i);a.set(t,0),Yu.sizeDataTexturePortionIds+=a.byteLength,Yu.numberOfTextures++;const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RED_INTEGER,e.UNSIGNED_SHORT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}}const qu=d.vec4([0,0,0,1]),Ju=d.vec4([0,0,0,1]);d.vec4([0,0,0,1]);const Zu=new Float32Array(16),$u=new Uint8Array(4),eh=new Float32Array(3),th=d.AABB3();let sh=0;const nh=d.identityMat4();class ih{constructor(e,t){Yu.numberOfLayers++,this._layerNumber=sh++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._dataTextureRenderers=function(e){const t=e.id;let s=Qu[t];return s||(s=new ku(e),Qu[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Qu[t],s._destroy()}))),s}(e.scene),this.model=e,this._buffer=new Wu,this._dataTextureState=new zu,this._dataTextureGenerator=new Xu,this._state=new Ke({origin:d.vec3(t.origin),metallicRoughnessBuf:null,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=d.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&Yu.cannotCreatePortion.because10BitsObjectId++;let s=this._numPortions+t<=65536;const n=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[n]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let n=0,i=0;e.buckets.forEach((e=>{n+=e.positionsCompressed.length/3,i+=e.indices.length/3})),(this._state.numVertices+n>16777216||t+i>16777216)&&Yu.cannotCreatePortion.becauseTextureSize++,s&&=this._state.numVertices+n<=16777216&&t+i<=16777216}return s}createPortion(e){if(this._finalized)throw"Already finalized";const t=[],s=e.worldAABB;e.buckets.forEach(((n,i)=>{const a=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#${i}`:`${e.id}#${i}`;let r=this._bucketGeometries[a];r||(r=this._createBucketGeometry(e,n),this._bucketGeometries[a]=r);const l=d.collapseAABB3(th),o=this._createSubPortion(e,r,n,l);d.expandAABB3(s,l),t.push(o)}));const n=this._state.origin;0===n[0]&&0===n[1]&&0===n[2]||(s[0]+=n[0],s[1]+=n[1],s[2]+=n[2],s[3]+=n[0],s[4]+=n[1],s[5]+=n[2]),d.expandAABB3(this.aabb,s);const i=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(t),this.model.numPortions++,i}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Yu.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;Yu.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,n=t.indices,i=t.edgeIndices,a=this._buffer;a.positionsCompressed.push(s);const r=a.lenPositionsCompressed/3,l=s.length/3;let o;a.lenPositionsCompressed+=s.length;let c,u=0;if(n){let e;u=n.length/3,l<=256?(e=a.indices8Bits,o=a.lenIndices8Bits/3,a.lenIndices8Bits+=n.length):l<=65536?(e=a.indices16Bits,o=a.lenIndices16Bits/3,a.lenIndices16Bits+=n.length):(e=a.indices32Bits,o=a.lenIndices32Bits/3,a.lenIndices32Bits+=n.length),e.push(n)}let h=0;if(i){let e;h=i.length/2,l<=256?(e=a.edgeIndices8Bits,c=a.lenEdgeIndices8Bits/2,a.lenEdgeIndices8Bits+=i.length):l<=65536?(e=a.edgeIndices16Bits,c=a.lenEdgeIndices16Bits/2,a.lenEdgeIndices16Bits+=i.length):(e=a.edgeIndices32Bits,c=a.lenEdgeIndices32Bits/2,a.lenEdgeIndices32Bits+=i.length),e.push(i)}this._state.numVertices+=l,Yu.numberOfGeometries++;const p=d.collapseAABB3();d.expandAABB3Points3(p,t.positionsCompressed),Pt.decompressAABB(p,e.positionsDecodeMatrix);return{vertexBase:r,numVertices:l,numTriangles:u,numEdges:h,indicesBase:o,edgeIndicesBase:c,aabb:p,obb:null}}_createSubPortion(e,t,s,n){const i=e.color;e.metallic,e.roughness;const a=e.colors,r=e.opacity,l=e.meshMatrix,o=e.pickColor,c=this._buffer,u=this._state;if(c.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),c.perObjectInstancePositioningMatrices.push(l||nh),l){t.obb||(t.obb=d.AABB3ToOBB3(t.aabb));const e=t.obb;for(let t=0,s=e.length;t<s;t+=4)qu[0]=e[t+0],qu[1]=e[t+1],qu[2]=e[t+2],qu[3]=1,l&&d.transformPoint4(l,qu,Ju),d.expandAABB3Point3(n,Ju)}else d.expandAABB3(n,t.aabb);c.perObjectSolid.push(!!e.solid),a?c.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):i&&c.perObjectColors.push([i[0],i[1],i[2],r]),c.perObjectPickColors.push(o),c.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,c.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?u.numEdgeIndices8Bits:t.numVertices<=65536?u.numEdgeIndices16Bits:u.numEdgeIndices32Bits,c.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const h=this._subPortions.length;if(t.numTriangles>0){let e,s=3*t.numTriangles;t.numVertices<=256?(e=c.perTriangleNumberPortionId8Bits,u.numIndices8Bits+=s,Yu.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=c.perTriangleNumberPortionId16Bits,u.numIndices16Bits+=s,Yu.totalPolygons16Bits+=t.numTriangles):(e=c.perTriangleNumberPortionId32Bits,u.numIndices32Bits+=s,Yu.totalPolygons32Bits+=t.numTriangles),Yu.totalPolygons+=t.numTriangles;for(let s=0;s<t.numTriangles;s+=8)e.push(h)}if(t.numEdges>0){let e,s=2*t.numEdges;t.numVertices<=256?(e=c.perEdgeNumberPortionId8Bits,u.numEdgeIndices8Bits+=s,Yu.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=c.perEdgeNumberPortionId16Bits,u.numEdgeIndices16Bits+=s,Yu.totalEdges16Bits+=t.numEdges):(e=c.perEdgeNumberPortionId32Bits,u.numEdgeIndices32Bits+=s,Yu.totalEdges32Bits+=t.numEdges),Yu.totalEdges+=t.numEdges;for(let s=0;s<t.numEdges;s+=8)e.push(h)}return this._subPortions.push({numVertices:t.numTriangles}),this._numPortions++,Yu.numberOfPortions++,h}finalize(){if(this._finalized)return;const e=this._state,t=this._dataTextureState,s=this.model.scene.canvas.gl,n=this._buffer;e.gl=s,t.texturePerObjectColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(s,n.perObjectColors,n.perObjectPickColors,n.perObjectVertexBases,n.perObjectIndexBaseOffsets,n.perObjectEdgeIndexBaseOffsets,n.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dataTextureGenerator.generateTextureForInstancingMatrices(s,n.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(s,n.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(s,n.positionsCompressed,n.lenPositionsCompressed),t.texturePerPolygonIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perTriangleNumberPortionId32Bits),n.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perEdgeNumberPortionId8Bits)),n.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perEdgeNumberPortionId16Bits)),n.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perEdgeNumberPortionId32Bits)),n.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,n.indices8Bits,n.lenIndices8Bits)),n.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,n.indices16Bits,n.lenIndices16Bits)),n.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,n.indices32Bits,n.lenIndices32Bits)),n.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(s,n.edgeIndices8Bits,n.lenEdgeIndices8Bits)),n.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(s,n.edgeIndices16Bits,n.lenEdgeIndices16Bits)),n.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(s,n.edgeIndices32Bits,n.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,s){t&H&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&k&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&W&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&j&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&G&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&U&&(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&H?(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&Q?(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&k?(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&W?(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&z?(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&j?(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.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(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&G?(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,n=s.length;e<n;e++)this._subPortionSetColor(s[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const s=this._dataTextureState,n=this.model.scene.canvas.gl;if($u[0]=t[0],$u[1]=t[1],$u[2]=t[2],$u[3]=t[3],s.texturePerObjectColorsAndFlags._textureData.set($u,32*e),this._deferredSetFlagsActive)return console.info("_subPortionSetColor defer"),void(this._deferredSetFlagsDirty=!0);++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,$u)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){const i=this._portionToSubPortionsMap[e];for(let e=0,a=i.length;e<a;e++)this._subPortionSetFlags(i[e],t,s,n)}_subPortionSetFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=!!(t&H),a=!!(t&k),r=!!(t&Q),l=!!(t&W),o=!!(t&U);let c,u;c=!i||o||a?sr.NOT_RENDERED:s?sr.COLOR_TRANSPARENT:sr.COLOR_OPAQUE,u=!i||o?sr.NOT_RENDERED:l?sr.SILHOUETTE_SELECTED:r?sr.SILHOUETTE_HIGHLIGHTED:a?sr.SILHOUETTE_XRAYED:sr.NOT_RENDERED;let h=0;h=!i||o?sr.NOT_RENDERED:l?sr.EDGES_SELECTED:r?sr.EDGES_HIGHLIGHTED:a?sr.EDGES_XRAYED:!!(t&z)?s?sr.EDGES_COLOR_TRANSPARENT:sr.EDGES_COLOR_OPAQUE:sr.NOT_RENDERED;let p=i&&!!(t&G)?sr.PICK:sr.NOT_RENDERED;const A=this._dataTextureState,d=this.model.scene.canvas.gl;$u[0]=c,$u[1]=u,$u[2]=h,$u[3]=p,A.texturePerObjectColorsAndFlags._textureData.set($u,32*e+8),this._deferredSetFlagsActive||n?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),d.bindTexture(d.TEXTURE_2D,A.texturePerObjectColorsAndFlags._texture),d.texSubImage2D(d.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,d.RGBA_INTEGER,d.UNSIGNED_BYTE,$u))}_setDeferredFlags(){}_setFlags2(e,t,s=!1){const n=this._portionToSubPortionsMap[e];for(let e=0,i=n.length;e<i;e++)this._subPortionSetFlags2(n[e],t,s)}_subPortionSetFlags2(e,t,s=!1){if(!this._finalized)throw"Not finalized";const n=t&j?255:0,i=this._dataTextureState,a=this.model.scene.canvas.gl;$u[0]=n,$u[1]=0,$u[2]=1,$u[3]=2,i.texturePerObjectColorsAndFlags._textureData.set($u,32*e+12),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),a.bindTexture(a.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),a.texSubImage2D(a.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,a.RGBA_INTEGER,a.UNSIGNED_BYTE,$u))}_setDeferredFlags2(){}setOffset(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,n=s.length;e<n;e++)this._subPortionSetOffset(s[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const s=this._dataTextureState,n=this.model.scene.canvas.gl;eh[0]=t[0],eh[1]=t[1],eh[2]=t[2],s.texturePerObjectOffsets._textureData.set(eh,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectOffsets._texture),n.texSubImage2D(n.TEXTURE_2D,0,0,e,1,1,n.RGB,n.FLOAT,eh))}setMatrix(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,n=s.length;e<n;e++)this._subPortionSetMatrix(s[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=this._dataTextureState,n=this.model.scene.canvas.gl;Zu.set(t),s.texturePerObjectInstanceMatrices._textureData.set(Zu,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectInstanceMatrices._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,n.RGBA,n.FLOAT,Zu))}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,sr.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,sr.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,sr.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,sr.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,sr.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,sr.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,sr.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,sr.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,sr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,sr.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 ah=d.vec4(4),rh=d.vec4(),lh=d.vec4(),oh=d.vec3([1,0,0]),ch=d.vec3([0,1,0]),uh=d.vec3([0,0,1]);d.vec3(3),d.vec3(3);const hh=d.identityMat4();class ph{constructor(e){this._model=e.model,this.id=e.id,this._parentTransform=e.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=d.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=d.identityMat4(new Float32Array(16)),this._worldMatrix=d.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,e.matrix?this.matrix=e.matrix:(this.scale=e.scale,this.position=e.position,e.quaternion||(this.rotation=e.rotation)),e.parent&&e.parent._addChildTransform(this)}_addChildTransform(e){this._childTransforms.push(e),e._parentTransform=this,e._setWorldMatrixDirty(),e._setAABBDirty()}_addMesh(e){this._meshes.push(e),e.transform=this}get parentTransform(){return this._parentTransform}get meshes(){return this._meshes}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._model.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._model.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=d.identityMat4()),this._localMatrix.set(e||hh),d.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return ah[0]=e[0],ah[1]=e[1],ah[2]=e[2],ah[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(ah,rh),d.mulQuaternions(this.quaternion,rh,lh),this.quaternion=lh,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return ah[0]=e[0],ah[1]=e[1],ah[2]=e[2],ah[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(ah,rh),d.mulQuaternions(rh,this.quaternion,rh),this}rotateX(e){return this.rotate(oh,e)}rotateY(e){return this.rotate(ch,e)}rotateZ(e){return this.rotate(uh,e)}translate(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateX(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateY(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateZ(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._transformDirty()}_transformDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._childTransforms.length;e<t;e++){const t=this._childTransforms[e];if(t._transformDirty(),t._meshes&&t._meshes.length>0){const e=t._meshes;for(let t=0,s=e.length;t<s;t++)e[t]._transformDirty()}}if(this._meshes&&this._meshes.length>0){const e=this._meshes;for(let t=0,s=e.length;t<s;t++)e[t]._transformDirty()}}_buildWorldMatrix(){const e=this.matrix;if(this._parentTransform)d.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._childTransforms)for(let t=0,s=e._childTransforms.length;t<s;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}const Ah=d.vec3();d.mat4();const dh=d.vec3([1,1,1]),fh=d.vec3([0,0,0]),Ih=d.vec3([0,0,0]),yh=d.identityQuaternion(),mh=d.identityMat4(),vh=new Uint8Array([255,255,255]);class wh extends O{constructor(e,t={}){super(e,t),this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!1,this._vboBatchingLayerScratchMemory=(tr++,er),this._textureTranscoder=t.textureTranscoder||Ac(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=d.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._transforms={},this._meshes={},this._entities={},this._scheduledMeshes={},this.renderFlags=new Vn,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=d.vec3(t.origin||[0,0,0]),this._position=d.vec3(t.position||[0,0,0]),this._rotation=d.vec3(t.rotation||[0,0,0]),this._quaternion=d.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=d.vec4(t.quaternion||[0,0,0,1]),t.rotation&&d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=d.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=d.mat4(),this._worldRotationMatrixConjugate=d.mat4(),this._matrix=d.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=d.mat4(),d.inverseMat4(this._matrix,this._worldNormalMatrix),d.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=d.mat4(),this._viewNormalMatrix=d.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new sc({id:"defaultColorTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new sc({id:"defaultMetalRoughTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),s=new sc({id:"defaultNormalsTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),n=new sc({id:"defaultEmissiveTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),i=new sc({id:"defaultOcclusionTexture",texture:new Pi({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=n,this._textures.defaultOcclusionTexture=i,this._textureSets.defaultTextureSet=new tc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:s,emissiveTexture:n,occlusionTexture:i})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||mh),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}get worldMatrix(){return this.matrix}get worldNormalMatrix(){return this._worldNormalMatrix}get viewMatrix(){return this._viewMatrix?(this._matrixDirty&&(this._rebuildMatrices(),this._viewMatrixDirty=!0),this._viewMatrixDirty&&(d.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}get viewNormalMatrix(){return this._viewNormalMatrix?(this._matrixDirty&&(this._rebuildMatrices(),this._viewMatrixDirty=!0),this._viewMatrixDirty&&(d.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}get backfaces(){return this._backfaces}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get entityList(){return this._entityList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){if(this._aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._entityList.length;e<t;e++)d.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}get visible(){return this.numVisibleLayerPortions>0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].visible=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].xrayed=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].highlighted=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].selected=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].edges=e;this.glRedraw()}get culled(){return this._culled}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].culled=e;this.glRedraw()}get clippable(){return this._clippable}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].clippable=e;this.glRedraw()}get collidable(){return this._collidable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].collidable=e}get pickable(){return this.numPickableLayerPortions>0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].pickable=e}get colorize(){return this._colorize}set colorize(e){this._colorize=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].colorize=e}get opacity(){return this._opacity}set opacity(e){this._opacity=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].opacity=e}get castsShadow(){return this._castsShadow}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get colorTextureEnabled(){return this._colorTextureEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}createQuantizationRange(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:Ur(e.aabb,d.mat4())}:this.error("[createQuantizationRange] Config missing: id")}createGeometry(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`[createGeometry] Param expected: indices (required for '${e.primitive}' primitive type)`),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Ur(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Hr(e.positions,t,e.positionsDecodeMatrix)}else e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed);if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,s=new Uint8Array(t.length);for(let e=0,n=t.length;e<n;e++)s[e]=255*t[e];e.colorsCompressed=s}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=vt(e.positions,e.indices,null,5):e.edgeIndices=vt(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets&&(this._dtxBuckets[e.id]=e.buckets),e.uv){const t=Pt.getUVBounds(e.uv),s=Pt.compressUVs(e.uv,t.min,t.max);e.uvCompressed=s.quantized,e.uvDecodeMatrix=s.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error(`[createGeometry] Unsupported value for 'primitive': '${e.primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);else this.error("[createGeometry] Config missing: id")}createTexture(e){const t=e.id;if(null==t)return void this.error("[createTexture] Config missing: id");if(this._textures[t])return void this.error("[createTexture] Texture already created: "+t);if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;let s=e.minFilter||1008;1006!==s&&1007!==s&&1008!==s&&1005!==s&&1004!==s&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),s=1008);let n=e.magFilter||1006;1006!==n&&1003!==n&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),n=1006);let i=e.wrapS||1e3;1001!==i&&1002!==i&&1e3!==i&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),i=1e3);let a=e.wrapT||1e3;1001!==a&&1002!==a&&1e3!==a&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),a=1e3);let r=e.wrapR||1e3;1001!==r&&1002!==r&&1e3!==r&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),r=1e3);let l=e.encoding||3e3;3e3!==l&&3001!==l&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),l=3e3);const o=new Pi({gl:this.scene.canvas.gl,minFilter:s,magFilter:n,wrapS:i,wrapT:a,wrapR:r,encoding:l});if(e.preloadColor&&o.setPreloadColor(e.preloadColor),e.image){const t=e.image;t.crossOrigin="Anonymous",o.setImage(t,{minFilter:s,magFilter:n,wrapS:i,wrapT:a,wrapR:r,flipY:e.flipY,encoding:l})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const c=new Image;c.onload=()=>{o.setImage(c,{minFilter:s,magFilter:n,wrapS:i,wrapT:a,wrapR:r,flipY:e.flipY,encoding:l}),this.glRedraw()},c.src=e.src;break;default:this._textureTranscoder?w.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],o).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,o).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 sc({id:t,texture:o})}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,n,i,a,r;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(n=this._textures[e.metallicRoughnessTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(i=this._textures[e.normalsTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(a=this._textures[e.emissiveTextureId],!a)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else a=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(r=this._textures[e.occlusionTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultOcclusionTexture;const l=new tc({id:t,model:this,colorTexture:s,metallicRoughnessTexture:n,normalsTexture:i,emissiveTexture:a,occlusionTexture:r});return this._textureSets[t]=l,l}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(this.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const s=new ph({id:e.id,model:this,parentTransform:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[s.id]=s,s}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?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||dh,s=e.position||fh,n=e.rotation||Ih;d.eulerToQuaternion(n,"XYZ",yh),e.meshMatrix=d.composeMat4(s,yh,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Ur(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):vh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),s=[];L(e.positions,s,t)&&(e.positions=s,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Hr(e.positions,t,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=vt(e.positions,e.indices,null,2):e.edgeIndices=vt(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=gh(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=[];L(e.positions,t,Ah)&&(e.positions=t,e.origin=d.addVec3(e.origin,Ah,d.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=vt(e.positions,e.indices,null,2):e.edgeIndices=vt(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?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return void this.error(`[createMesh] Transform not found: ${e.transformId} - ensure that you create it first with createTransform()`)}else if(e.matrix)e.meshMatrix=e.matrix.slice();else{const t=e.scale||dh,s=e.position||fh,n=e.rotation||Ih;d.eulerToQuaternion(n,"XYZ",yh),e.meshMatrix=d.composeMat4(s,yh,t,d.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])]):vh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=gh(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t,Eh(e)}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])]):vh,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]),Eh(e.geometry)}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createMesh(e){const t=new $a(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);const s=t.pickId,n=s>>24&255,i=s>>16&255,a=s>>8&255,r=255&s;switch(e.pickColor=new Uint8Array([r,a,i,n]),e.worldAABB=d.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=d.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)}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.obb=e.obb||(e.geometry?e.geometry.obb:null),t.numPrimitives=e.numPrimitives,d.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let s=0,n=e.buckets.length;s<n;s++)t+=e.buckets[s].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(let s=0,n=e.buckets.length;s<n;s++)t+=e.buckets[s].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:const s=e.geometry;t+=s.positions?s.positions.length:s.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(let s=0,n=e.buckets.length;s<n;s++)t+=e.buckets[s].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}_getDTXLayer(e){const t=e.origin,s=`${Math.round(t[0])}.${Math.round(t[1])}.${Math.round(t[2])}`;let n=this._dtxLayers[s];if(n){if(n.canCreatePortion(e))return n;n.finalize(),delete this._dtxLayers[s],n=null}return n=new ih(this,{layerIndex:0,origin:t}),this._dtxLayers[s]=n,this.layerList.push(n),n}_getVBOBatchingLayer(e){const t=this,s=e.origin,n=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",i=e.textureSetId||"-",a=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${e.primitive}.${n}.${i}`;let r=this._vboBatchingLayers[a];if(r)return r;let l=e.textureSet;for(;!r;){switch(e.primitive){case"triangles":case"solid":case"surface":r=new Al({model:t,textureSet:l,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:s,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0});break;case"lines":r=new Ao({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:s,maxGeometryBatchSize:this._maxGeometryBatchSize});break;case"points":r=new Ho({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:s,maxGeometryBatchSize:this._maxGeometryBatchSize})}const n=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?r.canCreatePortion(n):r.canCreatePortion(n,e.indices.length))||(r.finalize(),delete this._vboBatchingLayers[a],r=null)}return this._vboBatchingLayers[a]=r,this.layerList.push(r),r}_createHashStringFromMatrix(e){const t=e.join("");let s=0;for(let e=0;e<t.length;e++){s=(s<<5)-s+t.charCodeAt(e),s|=0}return(s>>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,s=e.origin,n=e.textureSetId||"-",i=e.geometryId,a=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${n}.${i}`;let r=this._vboInstancingLayers[a];if(r)return r;let l=e.textureSet;const o=e.geometry;for(;!r;)switch(o.primitive){case"triangles":case"surface":r=new ao({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0,solid:!1});break;case"solid":r=new ao({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0,solid:!0});break;case"lines":r=new Do({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0});break;case"points":r=new ec({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0})}return this._vboInstancingLayers[a]=r,this.layerList.push(r),r}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=H),this._pickable&&!1!==e.pickable&&(t|=G),this._culled&&!1!==e.culled&&(t|=U),this._clippable&&!1!==e.clippable&&(t|=j),this._collidable&&!1!==e.collidable&&(t|=V),this._edges&&!1!==e.edges&&(t|=z),this._xrayed&&!1!==e.xrayed&&(t|=k),this._highlighted&&!1!==e.highlighted&&(t|=Q),this._selected&&!1!==e.selected&&(t|=W),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];const s=d.collapseAABB3();for(let n=0,i=e.meshIds.length;n<i;n++){const i=e.meshIds[n],a=this._meshes[i];a?a.parent?this.error(`Mesh with ID "${i}" already belongs to object with ID "${a.parent.id}" - ignoring this mesh`):(d.expandAABB3(s,a.aabb),t.push(a)):this.error(`Mesh with this ID not found: "${i}" - ignoring this mesh`)}const n=new X(this,e.isObject,e.id,t,e.flags,s,!0);this._entityList.push(n),this._entities[e.id]=n,this.numEntities++}finalize(){if(!this.destroyed){for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].finalize()}this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._dtxLayers={},this._vboInstancingLayers={},this._vboBatchingLayers={};for(let e=0,t=this._entityList.length;e<t;e++){this._entityList[e]._finalize()}for(let e=0,t=this._entityList.length;e<t;e++){this._entityList[e]._finalize2()}this.layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].layerIndex=e}this.glRedraw(),this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position}}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,s=this.layerList.length;t<s;t++){const s=this.layerList[t];this._getActiveSectionPlanesForLayer(s)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,s=this.scene._sectionPlanesState.sectionPlanes,n=s.length,i=e.layerIndex*n;if(n>0)for(let e=0;e<n;e++){s[e].active?(t.sectionPlanesActivePerLayer[i+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[i+e]=!1}return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawColorOpaque(t,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawShadow(t,e)}}setPickMatrices(e,t){if(0===this._numVisibleLayerPortions)return;const s=this.renderFlags;for(let n=0,i=s.visibleLayers.length;n<i;n++){const i=s.visibleLayers[n],a=this.layerList[i];a.setPickMatrices&&a.setPickMatrices(e,t)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawPickNormals(t,e)}}drawSnapInitDepthBuf(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s],i=this.layerList[n];i.drawSnapInitDepthBuf&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,i.drawSnapInitDepthBuf(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}drawSnapDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s],i=this.layerList[n];i.drawSnapDepths&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,i.drawSnapDepths(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}destroy(){for(let e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();this._vboBatchingLayers={};for(let e in this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(e)&&this._vboInstancingLayers[e].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(let e=0,t=this.layerList.length;e<t;e++)this.layerList[e].destroy();this.layerList=[];for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._destroy();this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==tr&&(tr--,0===tr&&er._clear()),super.destroy()}}function gh(e,t,s){let n,i,a,r;if(t||s?[n,i,a]=yc({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(n=e.positionsCompressed,i=e.indices,a=e.edgeIndices),s){r=Ec({positionsCompressed:n,indices:i,edgeIndices:a},n.length/3>65536?16:8)}else r=[{positionsCompressed:n,indices:i,edgeIndices:a}];return r}function Eh(e){if(e.obb=d.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Pt.decompressAABB(t,e.positionsDecodeMatrix),d.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positions),d.AABB3ToOBB3(t,e.obb)}else if(e.buckets){const t=d.collapseAABB3();for(let s=0,n=e.buckets.length;s<n;s++){const n=e.buckets[s];d.expandAABB3Points3(t,n.positionsCompressed)}Pt.decompressAABB(t,e.positionsDecodeMatrix),d.AABB3ToOBB3(t,e.obb)}}class Th extends wh{constructor(e,t={}){super(e,t)}}class bh extends O{constructor(e,t={}){super(e,t),this._skyboxMesh=new $n(this,{geometry:new _t(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new xt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Si(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class Dh{transcode(e,t,s={}){}destroy(){}}const Ph=d.vec4(),Rh=d.vec4(),Ch=d.vec3(),_h=d.vec3(),Bh=d.vec3(),Oh=d.vec4(),Sh=d.vec4(),Nh=d.vec4();class xh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,s){let n=!1;const i=this._scene.camera;if(e){const t=d.subVec3(e,i.eye,Ch);n=d.lenVec3(t)<s}if("perspective"===i.projection){i.ortho.scale=i.ortho.scale-s;const n=this._unproject(t,Oh),a=d.subVec3(n,i.eye,Nh),r=d.mulVec3Scalar(d.normalizeVec3(a),-s,[]);if(i.eye=[i.eye[0]-r[0],i.eye[1]-r[1],i.eye[2]-r[2]],i.look=[i.look[0]-r[0],i.look[1]-r[1],i.look[2]-r[2]],e){const t=d.subVec3(e,i.eye,Ch),s=d.lenVec3(t),n=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(i.look,i.eye,_h)),s);i.look=[i.eye[0]+n[0],i.eye[1]+n[1],i.eye[2]+n[2]]}}else if("ortho"===i.projection){const e=this._unproject(t,Oh);i.ortho.scale=i.ortho.scale-s,i.ortho._update();const n=this._unproject(t,Sh),a=d.subVec3(n,e,Nh),r=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(i.look,i.eye,Ch)),-s,_h),l=d.addVec3(a,r,Bh);i.eye=[i.eye[0]-l[0],i.eye[1]-l[1],i.eye[2]-l[2]],i.look=[i.look[0]-l[0],i.look[1]-l[1],i.look[2]-l[2]]}return n}_unproject(e,t){const s=this._scene.camera,n=s.project.transposedMatrix,i=n.subarray(8,12),a=n.subarray(12),r=[0,0,-1,1],l=d.dotVec4(r,i)/d.dotVec4(r,a);return s.project.unproject(e,l,Ph,Rh,t),t}destroy(){}}const Lh=d.vec3(),Mh=d.vec3(),Fh=d.vec3(),Hh=d.vec4(),Uh=d.vec4(),Gh=d.vec4();class jh{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=d.vec3(),this._cameraOffset=d.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=d.vec3(),this._rtcPos=d.vec3(),this._pivotViewPos=d.vec4(),this._pivotProjPos=d.vec4(),this._pivotCanvasPos=d.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const s=d.distVec3(t,e);let n=Math.tan(Math.PI/500)*s*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(n/=this._scene.camera.ortho.scale/2),x(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Mi(this._scene,si({radius:n})),this._pivotSphere=new $n(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const s=t.boundary,n=s[2],i=s[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*n/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*i/2);let a=t._lastBoundingClientRect;if(!a||t._canvasSizeChanged){const e=t.canvas;a=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(a.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(a.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),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new xt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const s=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,s),t=d.inverseMat4(t);const n=d.transformVec3(t,this._cameraOffset),i=d.vec3();if(d.subVec3(e.eye,s,i),d.addVec3(i,n),e.zUp){const e=i[1];i[1]=i[2],i[2]=e}this._radius=d.lenVec3(i),this._polar=Math.acos(i[1]/this._radius),this._azimuth=Math.atan2(i[0],i[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,Lh)),s=d.cross3Vec3(t,e.worldUp,Mh);return d.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(d.distVec3(this._scene.center,t.eye)),n=t.project.transposedMatrix,i=n.subarray(8,12),a=n.subarray(12),r=[0,0,-1,1],l=d.dotVec4(r,i)/d.dotVec4(r,a),o=Hh;t.project.unproject(e,l,Uh,Gh,o);const c=d.normalizeVec3(d.subVec3(o,t.eye,Lh)),u=d.addVec3(t.eye,d.mulVec3Scalar(c,s,Mh),Fh);this.setPivotPos(u)}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 n=-e;const i=-t;1===s.worldUp[2]&&(n=-n),this._azimuth+=.01*-n,this._polar+=.01*i,this._polar=d.clamp(this._polar,.001,Math.PI-.001);const a=[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=a[1];a[1]=a[2],a[2]=e}const r=d.lenVec3(d.subVec3(s.look,s.eye,d.vec3())),l=this.getPivotPos();d.addVec3(a,l);let o=d.lookAtMat4v(a,l,s.worldUp);o=d.inverseMat4(o);const c=d.transformVec3(o,this._cameraOffset);o[12]-=c[0],o[13]-=c[1],o[14]-=c[2];const u=[o[8],o[9],o[10]];s.eye=[o[12],o[13],o[14]],d.subVec3(s.eye,d.mulVec3Scalar(u,r),s.look),s.up=[o[4],o[5],o[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 Vh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._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 ve;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 kh=d.vec2();class Qh{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController;let r,l,o,c=0,u=0,h=0,p=0,A=!1;const f=d.vec3();let I=!0;const y=this._scene.canvas.canvas,m=[];function v(e=!0){y.style.cursor="move",c=n.pointerCanvasPos[0],u=n.pointerCanvasPos[1],h=n.pointerCanvasPos[0],p=n.pointerCanvasPos[1],e&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.picked&&a.pickedSurface&&a.pickResult&&a.pickResult.worldPos?(A=!0,f.set(a.pickResult.worldPos)):A=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const n=t.keyCode;m[n]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const n=t.keyCode;m[n]=!1}),y.addEventListener("mousedown",this._mouseDownHandler=t=>{if(s.active&&s.pointerEnabled)switch(t.which){case 1:m[e.input.KEY_SHIFT]||s.planView?(r=!0,v()):(r=!0,v(!1));break;case 2:l=!0,v();break;case 3:o=!0,s.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!s.active||!s.pointerEnabled)return;if(!r&&!l&&!o)return;const t=e.canvas.boundary,a=t[2],h=t[3],p=n.pointerCanvasPos[0],I=n.pointerCanvasPos[1];if(m[e.input.KEY_SHIFT]||s.planView||!s.panRightClick&&l||s.panRightClick&&o){const t=p-c,s=I-u,n=e.camera;if("perspective"===n.projection){const a=Math.abs(A?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(n.perspective.fov/2*Math.PI/180);i.panDeltaX+=1.5*t*a/h,i.panDeltaY+=1.5*s*a/h}else i.panDeltaX+=.5*n.ortho.scale*(t/h),i.panDeltaY+=.5*n.ortho.scale*(s/h)}else!r||l||o||s.planView||(s.firstPerson?(i.rotateDeltaY-=(p-c)/a*s.dragRotationRate/2,i.rotateDeltaX+=(I-u)/h*(s.dragRotationRate/4)):(i.rotateDeltaY-=(p-c)/a*(1.5*s.dragRotationRate),i.rotateDeltaX+=(I-u)/h*(1.5*s.dragRotationRate)));c=p,u=I}),y.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{s.active&&s.pointerEnabled&&n.mouseover&&(I=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:r=!1,l=!1,o=!1}}),y.addEventListener("mouseup",this._mouseUpHandler=e=>{if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){let s=e.target,n=0,i=0,a=0,r=0;for(;s.offsetParent;)n+=s.offsetLeft,i+=s.offsetTop,a+=s.scrollLeft,r+=s.scrollTop,s=s.offsetParent;t[0]=e.pageX+a-n,t[1]=e.pageY+r-i}else e=window.event,t[0]=e.x,t[1]=e.y}(e,kh);const s=kh[0],n=kh[1];Math.abs(s-h)<3&&Math.abs(n-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:kh,event:e},!0)}y.style.removeProperty("cursor")}}),y.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.active&&s.pointerEnabled});const w=1/60;let g=null;y.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=performance.now()/1e3;var a=null!==g?t-g:0;g=t,a>.05&&(a=.05),a<w&&(a=w);const r=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===r)return;const l=r/Math.abs(r);i.dollyDelta+=-l*a*s.mouseWheelDollyRate,I&&(n.followPointerDirty=!0,I=!1)},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const Wh=d.vec3(),zh=d.vec3(),Kh=d.vec3(),Yh=d.vec3(),Xh=d.vec3(),qh={eye:d.vec3(),look:d.vec3(),up:d.vec3()};class Jh{constructor(e,t,s,n){this._scene=e;const i=t.cameraControl,a=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!n.mouseover)return;const r=i._isKeyDownForAction(i.AXIS_VIEW_RIGHT),l=i._isKeyDownForAction(i.AXIS_VIEW_BACK),o=i._isKeyDownForAction(i.AXIS_VIEW_LEFT),c=i._isKeyDownForAction(i.AXIS_VIEW_FRONT),u=i._isKeyDownForAction(i.AXIS_VIEW_TOP),h=i._isKeyDownForAction(i.AXIS_VIEW_BOTTOM);if(!(r||l||o||c||u||h))return;const p=e.aabb,A=d.getAABB3Diag(p);d.getAABB3Center(p,Wh);const f=Math.abs(A/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),I=1.1*A;qh.orthoScale=I,r?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldRight,f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):l?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldForward,f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):o?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldRight,-f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):c?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldForward,-f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):u?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldUp,f,zh),Xh)),qh.look.set(Wh),qh.up.set(d.normalizeVec3(d.mulVec3Scalar(a.worldForward,1,Kh),Yh))):h&&(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldUp,-f,zh),Xh)),qh.look.set(Wh),qh.up.set(d.normalizeVec3(d.mulVec3Scalar(a.worldForward,-1,Kh)))),!s.firstPerson&&s.followPointer&&t.pivotController.setPivotPos(Wh),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 Zh{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController,r=t.pivotController,l=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let o=!1,c=!1;const u=this._scene.canvas.canvas,h=s=>{let n;s&&s.worldPos&&(n=s.worldPos);const i=s&&s.entity?s.entity.aabb:e.aabb;if(n){const s=e.camera;d.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:i})}else t.cameraFlight.flyTo({aabb:i})};u.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(o||c)return;const i=l.hasSubs("hover"),r=l.hasSubs("hoverEnter"),u=l.hasSubs("hoverOut"),h=l.hasSubs("hoverOff"),p=l.hasSubs("hoverSurface"),A=l.hasSubs("hoverSnapOrSurface");if(i||r||u||h||p||A)if(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=p,a.scheduleSnapOrPick=A,a.update(),a.pickResult){if(a.pickResult.entity){const t=a.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&l.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),l.fire("hoverEnter",a.pickResult,!0),this._lastPickedEntityId=t)}l.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&l.fire("hoverSurface",a.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(l.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),l.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}),u.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(o=!0),3===t.which&&(c=!0);if(1===t.which&&s.active&&s.pointerEnabled&&(n.mouseDownClientX=t.clientX,n.mouseDownClientY=t.clientY,n.mouseDownCursorX=n.pointerCanvasPos[0],n.mouseDownCursorY=n.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===t.which))){const t=a.pickResult;t&&t.worldPos?(r.setPivotPos(t.worldPos),r.startPivot()):(s.smartPivot?r.setCanvasPivotPos(n.pointerCanvasPos):r.setPivotPos(e.camera.look),r.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(o=!1),3===e.which&&(c=!1),r.getPivoting()&&r.endPivot()}),u.addEventListener("mouseup",this._canvasMouseUpHandler=i=>{if(!s.active||!s.pointerEnabled)return;if(!(1===i.which))return;if(r.hidePivot(),Math.abs(i.clientX-n.mouseDownClientX)>3||Math.abs(i.clientY-n.mouseDownClientY)>3)return;const o=l.hasSubs("picked"),c=l.hasSubs("pickedNothing"),u=l.hasSubs("pickedSurface"),p=l.hasSubs("doublePicked"),A=l.hasSubs("doublePickedSurface"),f=l.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||p||A||f))return(o||c||u)&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=u,a.update(),a.pickResult?(l.fire("picked",a.pickResult,!0),a.pickedSurface&&l.fire("pickedSurface",a.pickResult,!0)):l.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo,a.schedulePickSurface=u,a.update();const e=a.pickResult,i=a.pickedSurface;this._timeout=setTimeout((()=>{e?(l.fire("picked",e,!0),i&&(l.fire("pickedSurface",e,!0),!s.firstPerson&&s.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):l.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0),this._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo||p||A,a.schedulePickSurface=a.schedulePickEntity&&A,a.update(),a.pickResult){if(l.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult,!0),s.doublePickFlyTo&&(h(a.pickResult),!s.firstPerson&&s.followPointer)){const e=a.pickResult.entity.aabb,s=d.getAABB3Center(e);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(l.fire("doublePickedNothing",{canvasPos:n.pointerCanvasPos},!0),s.doublePickFlyTo&&(h(),!s.firstPerson&&s.followPointer)){const s=e.aabb,n=d.getAABB3Center(s);t.pivotController.setPivotPos(n),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 $h{constructor(e,t,s,n,i){this._scene=e;const a=e.input,r=[],l=e.canvas.canvas;let o=!0;this._onSceneMouseMove=a.on("mousemove",(()=>{o=!0})),this._onSceneKeyDown=a.on("keydown",(t=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&n.mouseover&&(r[t]=!0,t===a.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=a.on("keyup",(n=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&(r[n]=!1,n===a.KEY_SHIFT&&(l.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(l=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!n.mouseover)return;const c=t.cameraControl,u=l.deltaTime/1e3;if(!s.planView){const e=c._isKeyDownForAction(c.ROTATE_Y_POS,r),n=c._isKeyDownForAction(c.ROTATE_Y_NEG,r),a=c._isKeyDownForAction(c.ROTATE_X_POS,r),l=c._isKeyDownForAction(c.ROTATE_X_NEG,r),o=u*s.keyboardRotationRate;(e||n||a||l)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),e?i.rotateDeltaY+=o:n&&(i.rotateDeltaY-=o),a?i.rotateDeltaX+=o:l&&(i.rotateDeltaX-=o),!s.firstPerson&&s.followPointer&&t.pivotController.startPivot())}if(!r[a.KEY_CTRL]&&!r[a.KEY_ALT]){const e=c._isKeyDownForAction(c.DOLLY_BACKWARDS,r),a=c._isKeyDownForAction(c.DOLLY_FORWARDS,r);if(e||a){const r=u*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),a?i.dollyDelta-=r:e&&(i.dollyDelta+=r),o&&(n.followPointerDirty=!0,o=!1)}}const h=c._isKeyDownForAction(c.PAN_FORWARDS,r),p=c._isKeyDownForAction(c.PAN_BACKWARDS,r),A=c._isKeyDownForAction(c.PAN_LEFT,r),d=c._isKeyDownForAction(c.PAN_RIGHT,r),f=c._isKeyDownForAction(c.PAN_UP,r),I=c._isKeyDownForAction(c.PAN_DOWN,r),y=(r[a.KEY_ALT]?.3:1)*u*s.keyboardPanRate;(h||p||A||d||f||I)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),I?i.panDeltaY+=y:f&&(i.panDeltaY+=-y),d?i.panDeltaX+=-y:A&&(i.panDeltaX+=y),p?i.panDeltaZ+=y:h&&(i.panDeltaZ+=-y))}))}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 ep=d.vec3();class tp{constructor(e,t,s,n,i){this._scene=e;const a=e.camera,r=t.pickController,l=t.pivotController,o=t.panController;let c=1,u=1,h=null;this._onTick=e.on("tick",(()=>{if(!s.active||!s.pointerEnabled)return;let t="default";if(Math.abs(i.dollyDelta)<.001&&(i.dollyDelta=0),Math.abs(i.rotateDeltaX)<.001&&(i.rotateDeltaX=0),Math.abs(i.rotateDeltaY)<.001&&(i.rotateDeltaY=0),0===i.rotateDeltaX&&0===i.rotateDeltaY||(i.dollyDelta=0),s.followPointer&&--c<=0&&(c=1,0!==i.dollyDelta)){if(0===i.rotateDeltaY&&0===i.rotateDeltaX&&s.followPointer&&n.followPointerDirty&&(r.pickCursorPos=n.pointerCanvasPos,r.schedulePickSurface=!0,r.update(),r.pickResult&&r.pickResult.worldPos?h=r.pickResult.worldPos:(u=1,h=null),n.followPointerDirty=!1),h){const t=Math.abs(d.lenVec3(d.subVec3(h,e.camera.eye,ep)));u=t/s.dollyProximityThreshold}u<s.dollyMinSpeed&&(u=s.dollyMinSpeed)}const p=i.dollyDelta*u;if(0===i.rotateDeltaY&&0===i.rotateDeltaX||(!s.firstPerson&&s.followPointer&&l.getPivoting()?(l.continuePivot(i.rotateDeltaY,i.rotateDeltaX),l.showPivot()):(0!==i.rotateDeltaX&&(s.firstPerson?a.pitch(-i.rotateDeltaX):a.orbitPitch(i.rotateDeltaX)),0!==i.rotateDeltaY&&(s.firstPerson?a.yaw(i.rotateDeltaY):a.orbitYaw(i.rotateDeltaY))),i.rotateDeltaX*=s.rotationInertia,i.rotateDeltaY*=s.rotationInertia,t="grabbing"),Math.abs(i.panDeltaX)<.001&&(i.panDeltaX=0),Math.abs(i.panDeltaY)<.001&&(i.panDeltaY=0),Math.abs(i.panDeltaZ)<.001&&(i.panDeltaZ=0),0!==i.panDeltaX||0!==i.panDeltaY||0!==i.panDeltaZ){const e=d.vec3();let n,r;if(e[0]=i.panDeltaX,e[1]=i.panDeltaY,e[2]=i.panDeltaZ,s.constrainVertical){a.xUp?(n=a.eye[0],r=a.look[0]):a.yUp?(n=a.eye[1],r=a.look[1]):a.zUp&&(n=a.eye[2],r=a.look[2]),a.pan(e);const t=a.eye,s=a.look;a.xUp?(t[0]=n,s[0]=r):a.yUp?(t[1]=n,s[1]=r):a.zUp&&(t[2]=n,s[2]=r),a.eye=t,a.look=s}else a.pan(e);t="grabbing"}if(i.panDeltaX*=s.panInertia,i.panDeltaY*=s.panInertia,i.panDeltaZ*=s.panInertia,0!==p){if(t=p<0?"zoom-in":"zoom-out",s.firstPerson){let e,t;if(s.constrainVertical&&(a.xUp?(e=a.eye[0],t=a.look[0]):a.yUp?(e=a.eye[1],t=a.look[1]):a.zUp&&(e=a.eye[2],t=a.look[2])),s.followPointer){o.dollyToCanvasPos(h,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0)}else a.pan([0,0,p]),a.ortho.scale=a.ortho.scale-p;if(s.constrainVertical){const s=a.eye,n=a.look;a.xUp?(s[0]=e,n[0]=t):a.yUp?(s[1]=e,n[1]=t):a.zUp&&(s[2]=e,n[2]=t),a.eye=s,a.look=n}}else if(s.planView)if(s.followPointer){o.dollyToCanvasPos(h,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0)}else a.ortho.scale=a.ortho.scale+p,a.zoom(p);else if(s.followPointer){o.dollyToCanvasPos(h,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0)}else a.ortho.scale=a.ortho.scale+p,a.zoom(p);i.dollyDelta*=s.dollyInertia}r.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class sp{constructor(e,t,s,n,i){this._scene=e;const a=this._scene.canvas.canvas;a.addEventListener("mouseenter",this._mouseEnterHandler=()=>{n.mouseover=!0}),a.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{n.mouseover=!1,a.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{np(e,a,n.pointerCanvasPos)}),a.addEventListener("mousedown",this._mouseDownHandler=e=>{s.active&&s.pointerEnabled&&(np(e,a,n.pointerCanvasPos),n.mouseover=!0)}),a.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 np(e,t,s){if(e){const{x:n,y:i}=t.getBoundingClientRect();s[0]=e.clientX-n,s[1]=e.clientY-i}else e=window.event,s[0]=e.x,s[1]=e.y;return s}const ip=function(e,t){if(e){let s=e.target,n=0,i=0;for(;s.offsetParent;)n+=s.offsetLeft,i+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-n,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class ap{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController,r=t.pivotController,l=d.vec2(),o=d.vec2(),c=d.vec2(),u=d.vec2(),h=[],p=this._scene.canvas.canvas;let A=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 i=t.touches,o=t.changedTouches;for(n.touchStartTime=Date.now(),1===i.length&&1===o.length&&(ip(i[0],l),s.followPointer&&(a.pickCursorPos=l,a.schedulePickSurface=!0,a.update(),s.planView||(a.picked&&a.pickedSurface&&a.pickResult&&a.pickResult.worldPos?(r.setPivotPos(a.pickResult.worldPos),!s.firstPerson&&r.startPivot()&&r.showPivot()):(s.smartPivot?r.setCanvasPivotPos(n.pointerCanvasPos):r.setPivotPos(e.camera.look),!s.firstPerson&&r.startPivot()&&r.showPivot()))));h.length<i.length;)h.push(d.vec2());for(let e=0,t=i.length;e<t;++e)ip(i[e],h[e]);A=i.length}),p.addEventListener("touchend",this._canvasTouchEndHandler=()=>{r.getPivoting()&&r.endPivot()}),p.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const r=e.canvas.boundary,l=r[2],p=r[3],I=t.touches;if(t.touches.length===A){if(1===A){ip(I[0],o),d.subVec2(o,h[0],u);const t=u[0],a=u[1];if(null!==n.longTouchTimeout&&(Math.abs(t)>s.longTapRadius||Math.abs(a)>s.longTapRadius)&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),s.planView){const n=e.camera;if("perspective"===n.projection){const r=Math.abs(e.camera.eyeLookDist)*Math.tan(n.perspective.fov/2*Math.PI/180);i.panDeltaX+=t*r/p*s.touchPanRate,i.panDeltaY+=a*r/p*s.touchPanRate}else i.panDeltaX+=.5*n.ortho.scale*(t/p)*s.touchPanRate,i.panDeltaY+=.5*n.ortho.scale*(a/p)*s.touchPanRate}else i.rotateDeltaY-=t/l*(1*s.dragRotationRate),i.rotateDeltaX+=a/p*(1.5*s.dragRotationRate)}else if(2===A){const t=I[0],r=I[1];ip(t,o),ip(r,c);const l=d.geometricMeanVec2(h[0],h[1]),u=d.geometricMeanVec2(o,c),A=d.vec2();d.subVec2(l,u,A);const f=A[0],y=A[1],m=e.camera,v=d.distVec2([t.pageX,t.pageY],[r.pageX,r.pageY]),w=(d.distVec2(h[0],h[1])-v)*s.touchDollyRate;if(i.dollyDelta=w,Math.abs(w)<1)if("perspective"===m.projection){const t=a.pickResult?a.pickResult.worldPos:e.center,n=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(m.perspective.fov/2*Math.PI/180);i.panDeltaX-=f*n/p*s.touchPanRate,i.panDeltaY-=y*n/p*s.touchPanRate}else i.panDeltaX-=.5*m.ortho.scale*(f/p)*s.touchPanRate,i.panDeltaY-=.5*m.ortho.scale*(y/p)*s.touchPanRate;n.pointerCanvasPos=u}for(let e=0;e<A;++e)ip(I[e],h[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}const rp=function(e,t){if(e){let s=e.target,n=0,i=0;for(;s.offsetParent;)n+=s.offsetLeft,i+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-n,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class lp{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController,r=t.cameraControl;let l;const o=[],c=new Float32Array(2);let u=-1,h=-1;const p=this._scene.canvas.canvas,A=s=>{let n;s&&s.worldPos&&(n=s.worldPos);const i=s?s.entity.aabb:e.aabb;if(n){const s=e.camera;d.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:i})}else t.cameraFlight.flyTo({aabb:i})};p.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!s.active||!s.pointerEnabled)return;null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null);const i=e.touches,a=e.changedTouches;if(l=Date.now(),1===i.length&&1===a.length){u=l,rp(i[0],c);const a=c[0],r=c[1],o=i[0].pageX,h=i[0].pageY;n.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(o),Math.round(h)],canvasPos:[Math.round(a),Math.round(r)],event:e},!0),n.longTouchTimeout=null}),s.longTapTimeout)}else u=-1;for(;o.length<i.length;)o.push(new Float32Array(2));for(let e=0,t=i.length;e<t;++e)rp(i[e],o[e]);o.length=i.length},{passive:!0}),p.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=Date.now(),i=e.touches,l=e.changedTouches,p=r.hasSubs("pickedSurface");null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),0===i.length&&1===l.length&&u>-1&&t-u<150&&(h>-1&&u-h<325?(rp(l[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=p,a.update(),a.pickResult?(a.pickResult.touchInput=!0,r.fire("doublePicked",a.pickResult),a.pickedSurface&&r.fire("doublePickedSurface",a.pickResult),s.doublePickFlyTo&&A(a.pickResult)):(r.fire("doublePickedNothing"),s.doublePickFlyTo&&A()),h=-1):d.distVec2(o[0],c)<4&&(rp(l[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=p,a.update(),a.pickResult?(a.pickResult.touchInput=!0,r.fire("picked",a.pickResult),a.pickedSurface&&r.fire("pickedSurface",a.pickResult)):r.fire("pickedNothing"),h=t),u=-1),o.length=i.length;for(let e=0,t=i.length;e<t;++e)o[e][0]=i[e].pageX,o[e][1]=i[e].pageY},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class op extends O{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const s=this.scene;this._controllers={cameraControl:this,pickController:new Vh(this,this._configs),pivotController:new jh(s,this._configs),panController:new xh(s),cameraFlight:new Ca(this,{duration:.5})},this._handlers=[new sp(this.scene,this._controllers,this._configs,this._states,this._updates),new ap(this.scene,this._controllers,this._configs,this._states,this._updates),new Qh(this.scene,this._controllers,this._configs,this._states,this._updates),new Jh(this.scene,this._controllers,this._configs,this._states,this._updates),new Zh(this.scene,this._controllers,this._configs,this._states,this._updates),new lp(this.scene,this._controllers,this._configs,this._states,this._updates),new $h(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new tp(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",w.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,n=s.length;e<n;e++){if(t[s[e]])return!0}return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}get active(){return this._configs.active}set snapToVertex(e){this._configs.snapToVertex=!!e}get snapToVertex(){return this._configs.snapToVertex}set snapToEdge(e){this._configs.snapToEdge=!!e}get snapToEdge(){return this._configs.snapToEdge}set snapRadius(e){e=e||30,this._configs.snapRadius=e}get snapRadius(){return this._configs.snapRadius}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}enablePivotSphere(e={}){this._controllers.pivotController.enablePivotSphere(e)}disablePivotSphere(){this._controllers.pivotController.disablePivotSphere()}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}set doubleClickTimeFrame(e){this._configs.doubleClickTimeFrame=null!=e?e:250}get doubleClickTimeFrame(){return this._configs.doubleClickTimeFrame}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class cp{constructor(e,t,s,n,i){this.name=e,this.type=s,this.value=t,this.valueType=n,this.description=i}}class up{constructor(e){if(this.id=e.id,this.originalSystemId=e.originalSystemId,this.metaModels=[],this.name=e.name,this.type=e.type,this.properties=[],e.properties){const t=e.properties;for(let e=0,s=t.length;e<s;e++){const s=t[e];this.properties.push(new cp(s.name,s.value,s.type,s.valueType,s.description))}}}}class hp{constructor(e){this.metaModels=[],this.id=e.id,this.parentId=e.parentId,this.parent=null,this.originalSystemId=e.originalSystemId,this.name=e.name,this.type=e.type,this.propertySetIds=e.propertySetIds,this.propertySets=[],this.attributes=e.attributes||{},void 0!==e.external&&null!==e.external&&(this.external=e.external)}get metaModel(){return 1==this.metaModels.length?this.metaModels[0]:null}getObjectIDsInSubtree(){const e=[];return function t(s){if(!s)return;e.push(s.id);const n=s.children;if(n)for(var i=0,a=n.length;i<a;i++)t(n[i])}(this),e}withMetaObjectsInSubtree(e){!function t(s){if(!s)return;e(s);const n=s.children;if(n)for(var i=0,a=n.length;i<a;i++)t(n[i])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var s=0,n=e.length;s<n;s++)t[e[s]]=e[s];const i=[];return function e(s){if(!s)return;t[s.type]&&i.push(s.id);const n=s.children;if(n)for(var a=0,r=n.length;a<r;a++)e(n[a])}(this),i}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class pp{constructor(e){this.id=e.id,this.projectId=e.projectId,this.revisionId=e.revisionId,this.author=e.author,this.createdAt=e.createdAt,this.creatingApplication=e.creatingApplication,this.schema=e.schema,this.metaScene=e.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects=[],this.graph=e.graph||{},this.metaScene.metaModels[this.id]=this,this.finalized=!1}get rootMetaObject(){return 1==this.rootMetaObjects.length?this.rootMetaObjects[0]:null}loadData(e,t={}){if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);const s=this.metaScene;if(e.propertySets)for(let t=0,n=e.propertySets.length;t<n;t++){const n=e.propertySets[t];let i=s.propertySets[n.id];i||(i=new up({id:n.id,originalSystemId:n.originalSystemId||n.id,type:n.type,name:n.name,properties:n.properties}),s.propertySets[i.id]=i),i.metaModels.push(this),this.propertySets.push(i)}if(e.metaObjects)for(let t=0,n=e.metaObjects.length;t<n;t++){const n=e.metaObjects[t],i=n.id;let a=s.metaObjects[i];if(!a){const e=n.type,t=n.originalSystemId,s=n.propertySets||n.propertySetIds;a=new hp({id:i,originalSystemId:t,parentId:n.parent,type:e,name:n.name,attributes:n.attributes,propertySetIds:s,external:n.external}),this.metaScene.metaObjects[i]=a}a.metaModels.push(this),n.parent||(this.rootMetaObjects.push(a),s.rootMetaObjects[i]=a),this.metaObjects.push(a)}}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const s=e.metaObjects[t];if(s.children&&(s.children=[]),s.propertySets&&(s.propertySets=[]),s.propertySetIds)for(let t=0,n=s.propertySetIds.length;t<n;t++){const n=s.propertySetIds[t],i=e.propertySets[n];s.propertySets.push(i)}}for(let t in e.metaObjects){const s=e.metaObjects[t];if(s.parentId){const t=e.metaObjects[s.parentId];t&&(s.parent=t,(t.children||(t.children=[])).push(s))}}e.metaObjectsByType={};for(let t in e.metaObjects){const s=e.metaObjects[t],n=s.type;(e.metaObjectsByType[n]||(e.metaObjectsByType[n]={}))[t]=s}this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}getJSON(){const e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]};for(let t=0,s=this.metaObjects.length;t<s;t++){const s=this.metaObjects[t],n={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name};s.parent&&(n.parent=s.parent.id),s.attributes&&(n.attributes=s.attributes),s.propertySetIds&&(n.propertySetIds=s.propertySetIds),e.metaObjects.push(n)}for(let t=0,s=this.propertySets.length;t<s;t++){const s=this.propertySets[t],n={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name,propertyies:[]};for(let e=0,t=s.properties.length;e<t;e++){const t=s.properties[e],i={id:t.id,description:t.description,type:t.type,name:t.name,value:t.value,valueType:t.valueType};n.properties.push(i)}e.propertySets.push(n)}return e}_globalizeIDs(e,t){const s=!!t.globalizeObjectIds;if(e.metaObjects)for(let t=0,n=e.metaObjects.length;t<n;t++){const n=e.metaObjects[t];if(n.originalSystemId=n.id,n.parent&&(n.originalParentSystemId=n.parent),s&&(n.id=d.globalizeObjectId(this.id,n.id),n.parent&&(n.parent=d.globalizeObjectId(this.id,n.parent))),s){const e=n.propertySetIds;if(e){const t=[];for(let s=0,n=e.length;s<n;s++)t.push(d.globalizeObjectId(this.id,e[s]));n.propertySetIds=t,n.originalSystemPropertySetIds=e}}else n.originalSystemPropertySetIds=n.propertySetIds}if(e.propertySets)for(let t=0,n=e.propertySets.length;t<n;t++){const n=e.propertySets[t];n.originalSystemId=n.id,s&&(n.id=d.globalizeObjectId(this.id,n.id))}}}class Ap{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}on(e,t){let 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,n=s.length;e<n;e++)s[e](t)}off(e){}createMetaModel(e,t,s={}){const n=new pp({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return n.loadData(t),n.finalize(),n}destroyMetaModel(e){const t=this.metaModels[e];if(t){if(t.propertySets)for(let s=0,n=t.propertySets.length;s<n;s++){const n=t.propertySets[s];if(1===n.metaModels.length)delete this.propertySets[n.id];else{const t=[];for(let s=0,i=n.metaModels.length;s<i;s++)n.metaModels[s].id!==e&&t.push(n.metaModels[s]);n.metaModels=t}}if(t.metaObjects)for(let e=0,s=t.metaObjects.length;e<s;e++){const s=t.metaObjects[e];s.type;const n=s.id;if(1===s.metaModels.length)delete this.metaObjects[n],s.parent||delete this.rootMetaObjects[n];else{const e=[],n=t.id;for(let t=0,i=s.metaModels.length;t<i;t++)s.metaModels[t].id!==n&&e.push(s.metaModels[t]);s.metaModels=e}}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.children&&(t.children=[]),t.propertySets&&(t.propertySets=[]),t.propertySetIds)for(let e=0,s=t.propertySetIds.length;e<s;e++){const s=t.propertySetIds[e],n=this.propertySets[s];t.propertySets.push(n)}}this.metaObjectsByType={};for(let e in this.metaObjects){const t=this.metaObjects[e],s=t.type;t.children&&(t.children=null),(this.metaObjectsByType[s]||(this.metaObjectsByType[s]={}))[e]=t}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.parentId){const e=this.metaObjects[t.parentId];e&&(t.parent=e,(e.children||(e.children=[])).push(t))}}delete this.metaModels[e],this.fire("metaModelDestroyed",e)}}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,s){const n=[],i=this.metaObjects[e],a=t&&t.length>0?dp(t):null,r=s&&s.length>0?dp(s):null,l=e=>{if(!e)return;var t=!0;(r&&r[e.type]||a&&!a[e.type])&&(t=!1),t&&n.push(e.id);const s=e.children;if(s)for(var i=0,o=s.length;i<o;i++)l(s[i])};return l(i),n}withMetaObjectsInSubtree(e,t){const s=this.metaObjects[e];s&&s.withMetaObjectsInSubtree(t)}}function dp(e){const t={};for(var s=0,n=e.length;s<n;s++)t[e[s]]=!0;return t}
|
|
17
|
+
**/let mc=null;function vc(e,t){const s=3*e,n=3*t;let i,a,r,l,o,c;const u=Math.min(i=mc[s],a=mc[s+1],r=mc[s+2]),h=Math.min(l=mc[n],o=mc[n+1],c=mc[n+2]);if(u!==h)return u-h;const p=Math.max(i,a,r),A=Math.max(l,o,c);return p!==A?p-A:0}let wc=null;function gc(e,t){let s=wc[2*e]-wc[2*t];return 0!==s?s:wc[2*e+1]-wc[2*t+1]}function Ec(e,t,s=!1){const n=e.positionsCompressed||[],i=function(e,t){const s=new Int32Array(e.length/3);for(let e=0,t=s.length;e<t;e++)s[e]=e;mc=new Int32Array(e.length);for(let s=0,n=e.length;s<n;s++)mc[s]=e[s]>>t;s.sort(vc);const n=new Int32Array(e.length);for(let t=0,i=s.length;t<i;t++)n[3*t+0]=e[3*s[t]+0],n[3*t+1]=e[3*s[t]+1],n[3*t+2]=e[3*s[t]+2];return n}(e.indices||[],t),a=function(e){if(0===(e||[]).length)return[];let t=new Int32Array(e.length/2);for(let e=0,s=t.length;e<s;e++)t[e]=e;for(let t=0,s=e.length;t<s;t+=2)if(e[t]>e[t+1]){let s=e[t];e[t]=e[t+1],e[t+1]=s}wc=new Int32Array(e),t.sort(gc);const s=new Int32Array(e.length);for(let n=0,i=t.length;n<i;n++)s[2*n+0]=e[2*t[n]+0],s[2*n+1]=e[2*t[n]+1];return s}(e.edgeIndices||[]);function r(e,t){if(e>t){let s=e;e=t,t=s}function s(s,n){return s!==e?e-s:n!==t?t-n:0}let n=0,i=(a.length>>1)-1;for(;n<=i;){const e=i+n>>1,t=s(a[2*e],a[2*e+1]);if(t>0)n=e+1;else{if(!(t<0))return e;i=e-1}}return-n-1}const l=new Int32Array(a.length/2);l.fill(0);const o=n.length/3;if(o>8*(1<<t))return[e];const c=new Int32Array(o);c.fill(-1);const u=[];function h(){c.fill(-1);const e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:u.length};return u.push(e),e}let p=h();for(let t=0,s=i.length;t<s;t+=3){let s=0;const o=i[t],u=i[t+1],A=i[t+2];if(-1===c[o]&&s++,-1===c[u]&&s++,-1===c[A]&&s++,s+p.numPositions>p.maxNumPositions&&(p=h()),p.bucketNumber>8)return[e];let d;-1===c[o]&&(c[o]=p.numPositions++,p.positionsCompressed.push(n[3*o]),p.positionsCompressed.push(n[3*o+1]),p.positionsCompressed.push(n[3*o+2])),-1===c[u]&&(c[u]=p.numPositions++,p.positionsCompressed.push(n[3*u]),p.positionsCompressed.push(n[3*u+1]),p.positionsCompressed.push(n[3*u+2])),-1===c[A]&&(c[A]=p.numPositions++,p.positionsCompressed.push(n[3*A]),p.positionsCompressed.push(n[3*A+1]),p.positionsCompressed.push(n[3*A+2])),p.indices.push(c[o]),p.indices.push(c[u]),p.indices.push(c[A]),(d=r(o,u))>=0&&0===l[d]&&(l[d]=1,p.edgeIndices.push(c[a[2*d]]),p.edgeIndices.push(c[a[2*d+1]])),(d=r(o,A))>=0&&0===l[d]&&(l[d]=1,p.edgeIndices.push(c[a[2*d]]),p.edgeIndices.push(c[a[2*d+1]])),(d=r(u,A))>=0&&0===l[d]&&(l[d]=1,p.edgeIndices.push(c[a[2*d]]),p.edgeIndices.push(c[a[2*d+1]]))}const A=t/8*2,d=t/8,f=2*n.length+(i.length+a.length)*A;let I=0,y=-n.length/3;return u.forEach((e=>{I+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*d,y+=e.positionsCompressed.length/3})),I>f?[e]:(s&&function(e,t){const s={},n={};let i=0;e.forEach((e=>{const t=e.indices,a=e.edgeIndices,r=e.positionsCompressed;for(let e=0,n=t.length;e<n;e+=3){const n=r[3*t[e]]+"_"+r[3*t[e]+1]+"_"+r[3*t[e]+2]+"/"+r[3*t[e+1]]+"_"+r[3*t[e+1]+1]+"_"+r[3*t[e+1]+2]+"/"+r[3*t[e+2]]+"_"+r[3*t[e+2]+1]+"_"+r[3*t[e+2]+2];s[n]=!0}i+=e.edgeIndices.length/2;for(let e=0,t=a.length;e<t;e+=2){const t=r[3*a[e]]+"_"+r[3*a[e]+1]+"_"+r[3*a[e]+2]+"/"+r[3*a[e+1]]+"_"+r[3*a[e+1]+1]+"_"+r[3*a[e+1]+2]+"/";n[t]=!0}}));{const e=t.indices;t.edgeIndices;const n=t.positionsCompressed;for(let t=0,i=e.length;t<i;t+=3){const i=n[3*e[t]]+"_"+n[3*e[t]+1]+"_"+n[3*e[t]+2]+"/"+n[3*e[t+1]]+"_"+n[3*e[t+1]+1]+"_"+n[3*e[t+1]+2]+"/"+n[3*e[t+2]]+"_"+n[3*e[t+2]+1]+"_"+n[3*e[t+2]+2];if(!(i in s))throw console.log("Not found "+i),"Ohhhh!"}}}(u,e),u)}const Tc=d.vec3(),bc=d.vec3(),Dc=d.vec3(),Pc=d.vec3(),Rc=d.vec4(),Cc=d.mat4();class _c{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a;if(!this._program&&(this._allocate(),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Tc;if(I){const t=d.transformPoint3(h,c,bc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(i.viewMatrix,e,Cc),f=Dc,f[0]=i.eye[0]-e[0],f[1]=i.eye[1]-e[1],f[2]=i.eye[2]-e[2]}else A=i.viewMatrix,f=i.eye;if(r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const m=n._sectionPlanesState.sectionPlanes.length;if(m>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,i=a.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Pc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Pe(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uLightAmbient=n.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const i=s.lights;let a;for(let e=0,t=i.length;e<t;e++)switch(a=i[e],a.type){case"dir":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=n.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=n.getLocation("lightDir"+e),this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e)}this._uSceneModelMatrix=n.getLocation("sceneModelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=n.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState.lights,a=t.camera.project;n.bind(),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=i.length;e<t;e++){const t=i[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const n=t.sao;if(n.possible){const t=s.drawingBufferWidth,i=s.drawingBufferHeight;Rc[0]=t,Rc[1]=i,Rc[2]=n.blendCutoff,Rc[3]=n.blendFactor,s.uniform4fv(this._uSAOParams,Rc),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// TrianglesDataTextureColorRenderer vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),a.push("uniform mat4 sceneModelMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),a.push("uniform highp sampler2D uTexturePerObjectMatrix;"),a.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),a.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),a.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),a.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),a.push("uniform vec3 uCameraEyeRtc;"),a.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("out float isPerspective;")),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++)i=s.lights[e],"ambient"!==i.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));n&&(a.push("out vec4 vWorldPosition;"),a.push("flat out uint vFlags2;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int polygonIndex = gl_VertexID / 3;"),a.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),a.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),a.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),a.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),a.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),a.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),a.push("if (int(flags.x) != renderPass) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("} else {"),a.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),a.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),a.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),a.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),a.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),a.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),a.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),a.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),a.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),a.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),a.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),a.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),a.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),a.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),a.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),a.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),a.push("if (color.a == 0u) {"),a.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),a.push(" return;"),a.push("};"),a.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),a.push("vec3 position;"),a.push("position = positions[gl_VertexID % 3];"),a.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),a.push("if (solid != 1u) {"),a.push("if (isPerspectiveMatrix(projMatrix)) {"),a.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),a.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("} else {"),a.push("if (viewNormal.z < 0.0) {"),a.push("position = positions[2 - (gl_VertexID % 3)];"),a.push("viewNormal = -viewNormal;"),a.push("}"),a.push("}"),a.push("}"),a.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),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;");for(let e=0,t=s.lights.length;e<t;e++)if(i=s.lights[e],"ambient"!==i.type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = vec3(color.rgb) / 255.0;"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags2 = flags2.r;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// TrianglesDataTextureColorRenderer 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("}")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Bc=new Float32Array([1,1,1]),Oc=d.vec3(),Sc=d.vec3(),Nc=d.vec3(),xc=d.vec3(),Lc=d.mat4();class Mc{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a,A=i.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,I;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==u[0]||0!==u[1]||0!==u[2]){const e=Oc;if(c){const t=Sc;d.transformPoint3(h,c,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]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,Lc),I=Nc,I[0]=i.eye[0]-e[0],I[1]=i.eye[1]-e[1],I[2]=i.eye[2]-e[2]}else f=A,I=i.eye;if(r.uniform3fv(this._uCameraEyeRtc,I),r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uWorldMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),s===sr.SILHOUETTE_XRAYED){const e=n.xrayMaterial._state,t=e.fillColor,s=e.fillAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.SILHOUETTE_HIGHLIGHTED){const e=n.highlightMaterial._state,t=e.fillColor,s=e.fillAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.SILHOUETTE_SELECTED){const e=n.selectedMaterial._state,t=e.fillColor,s=e.fillAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else r.uniform4fv(this._uColor,Bc);if(n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const y=n._sectionPlanesState.sectionPlanes.length;if(y>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,i=a.renderFlags;for(let t=0;t<y;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,xc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture silhouette vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push("if (isPerspectiveMatrix(projMatrix)) {"),s.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Triangles dataTexture 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = color;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Fc=new Float32Array([0,0,0,1]),Hc=d.vec3(),Uc=d.vec3(),Gc=d.vec3(),jc=d.mat4();class Vc{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=a.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Hc;if(I){const t=d.transformPoint3(h,c,Uc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,jc)}else f=A;if(r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),s===sr.EDGES_XRAYED){const e=i.xrayMaterial._state,t=e.edgeColor,s=e.edgeAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.EDGES_HIGHLIGHTED){const e=i.highlightMaterial._state,t=e.edgeColor,s=e.edgeAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else if(s===sr.EDGES_SELECTED){const e=i.selectedMaterial._state,t=e.edgeColor,s=e.edgeAlpha;r.uniform4f(this._uColor,t[0],t[1],t[2],s)}else r.uniform4fv(this._uColor,Fc);const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Gc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(r.LINES,0,l.numEdgeIndices8Bits)),l.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(r.LINES,0,l.numEdgeIndices16Bits)),l.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(r.LINES,0,l.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,n=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&n.push("#extension GL_EXT_frag_depth : enable"),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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vColor;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const kc=d.vec3(),Qc=d.vec3(),Wc=d.vec3(),zc=d.mat4();class Kc{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=a.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=kc;if(I){const t=d.transformPoint3(h,c,Qc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,zc)}else f=A;r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Wc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(r.LINES,0,l.numEdgeIndices8Bits)),l.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(r.LINES,0,l.numEdgeIndices16Bits)),l.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(r.LINES,0,l.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=this._program,n=e.camera.project;if(s.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// 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 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform highp sampler2D uObjectPerObjectOffsets;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// TrianglesDataTextureEdgesColorRenderer"),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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vColor;"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yc=d.vec3(),Xc=d.vec3(),qc=d.vec3(),Jc=d.mat4();class Zc{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n;let A,f;o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Yc;if(I){const t=d.transformPoint3(h,c,Xc);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(a.viewMatrix,e,Jc),f=qc,f[0]=a.eye[0]-e[0],f[1]=a.eye[1]-e[1],f[2]=a.eye[2]-e[2]}else A=a.viewMatrix,f=a.eye;if(r.uniform2fv(this._uPickClipPos,e.pickClipPos),r.uniform2f(this._uDrawingBufferSize,r.drawingBufferWidth,r.drawingBufferHeight),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.project.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,e)}const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Yc);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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*objectDecodeAndInstanceMatrix)) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking 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;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uvec4 vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outPickColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (float(vFlags2.x) > 0.0);"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outPickColor = vPickColor; "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $c=d.vec3(),eu=d.vec3(),tu=d.vec3(),su=d.vec3(),nu=d.mat4();class iu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=e.pickViewMatrix||a.viewMatrix;let f,I;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==u[0]||0!==u[1]||0!==u[2]){const t=$c;if(c){const e=eu;d.transformPoint3(h,c,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]+=u[0],t[1]+=u[1],t[2]+=u[2],f=N(A,t,nu),I=tu,I[0]=a.eye[0]-t[0],I[1]=a.eye[1]-t[1],I[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=A,I=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(r.uniform3fv(this._uCameraEyeRtc,I),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniform2fv(this._uPickClipPos,e.pickClipPos),r.uniform2f(this._uDrawingBufferSize,r.drawingBufferWidth,r.drawingBufferHeight),r.uniform1f(this._uPickZNear,e.pickZNear),r.uniform1f(this._uPickZFar,e.pickZFar),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,a=n.renderFlags;for(let t=0;t<y;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,su);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles dataTexture pick depth vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform bool pickInvisible;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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*objectDecodeAndInstanceMatrix)) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=[];if(n.push("#version 300 es"),n.push("// Triangles dataTexture pick depth 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 float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outPackedDepth;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outPackedDepth = packDepth(zNormalizedDepth); "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const au=d.vec3(),ru=d.vec3(),lu=d.vec3(),ou=d.vec3(),cu=d.vec3(),uu=d.mat4();class hu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=t.aabb,f=e.pickViewMatrix||a.viewMatrix,I=au;let y,m;I[0]=d.safeInv(A[3]-A[0])*d.MAX_INT,I[1]=d.safeInv(A[4]-A[1])*d.MAX_INT,I[2]=d.safeInv(A[5]-A[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(I[0]),e.snapPickCoordinateScale[1]=d.safeInv(I[1]),e.snapPickCoordinateScale[2]=d.safeInv(I[2]),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==c[0]||0!==c[1]||0!==c[2],w=0!==u[0]||0!==u[1]||0!==u[2];if(v||w){const t=ru;if(v){const e=d.transformPoint3(h,c,lu);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=u[0],t[1]+=u[1],t[2]+=u[2],y=N(f,t,uu),m=ou,m[0]=a.eye[0]-t[0],m[1]=a.eye[1]-t[1],m[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else y=f,m=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,m),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,I),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,y),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const g=i._sectionPlanesState.sectionPlanes.length;if(g>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*g,a=n.renderFlags;for(let t=0;t<g;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,cu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}const E="edge"===e.snapMode?r.LINES:r.POINTS;l.numEdgeIndices8Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),r.drawArrays(E,0,l.numEdgeIndices8Bits)),l.numEdgeIndices16Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),r.drawArrays(E,0,l.numEdgeIndices16Bits)),l.numEdgeIndices32Bits>0&&(o.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),r.drawArrays(E,0,l.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=s.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("uSnapVectorA"),this.uInverseVectorAB=s.getLocation("uSnapInvVectorAB"),this._uLayerNumber=s.getLocation("uLayerNumber"),this._uCoordinateScaler=s.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("uniform mat4 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),s.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),s.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),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,n=e.sectionPlanes.length;t<n;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("out highp ivec4 outCoords;"),s.push("void main(void) {"),t){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 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 pu=d.vec3(),Au=d.vec3(),du=d.vec3(),fu=d.vec3(),Iu=d.vec3(),yu=d.mat4();class mu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=t.aabb,f=e.pickViewMatrix||a.viewMatrix,I=pu;let y,m;I[0]=d.safeInv(A[3]-A[0])*d.MAX_INT,I[1]=d.safeInv(A[4]-A[1])*d.MAX_INT,I[2]=d.safeInv(A[5]-A[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(I[0]),e.snapPickCoordinateScale[1]=d.safeInv(I[1]),e.snapPickCoordinateScale[2]=d.safeInv(I[2]),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==c[0]||0!==c[1]||0!==c[2],w=0!==u[0]||0!==u[1]||0!==u[2];if(v||w){const t=Au;if(v){const e=du;d.transformPoint3(h,c,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]+=u[0],t[1]+=u[1],t[2]+=u[2],y=N(f,t,yu),m=fu,m[0]=a.eye[0]-t[0],m[1]=a.eye[1]-t[1],m[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else y=f,m=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,m),r.uniform2fv(this._uVectorA,e.snapVectorA),r.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,I),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,y),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const g=i._sectionPlanesState.sectionPlanes.length;if(g>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*g,a=n.renderFlags;for(let t=0;t<g;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Iu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=s.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this._uVectorA=s.getLocation("uVectorAB"),this._uInverseVectorAB=s.getLocation("uInverseVectorAB"),this._uLayerNumber=s.getLocation("uLayerNumber"),this._uCoordinateScaler=s.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// 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 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),s.push("{"),s.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),s.push("if (solid != 1u) {"),s.push(" if (isPerspectiveMatrix(projMatrix)) {"),s.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vWorldPosition = worldPosition;"),t&&s.push("vFlags2 = flags2.r;"),s.push("vPickColor = vec4(texelFetch (uTexturePerObjectIdColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),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;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("flat in uint vFlags2;");for(let t=0,n=e.sectionPlanes.length;t<n;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("layout(location = 0) out highp ivec4 outCoords;"),s.push("layout(location = 1) out highp ivec4 outNormal;"),s.push("layout(location = 2) out lowp uvec4 outPickColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 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("vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vu=d.vec3(),wu=d.vec3(),gu=d.vec3(),Eu=d.vec3(),Tu=d.mat4();class bu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=n,A=e.pickViewMatrix||a.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,I;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==u[0]||0!==u[1]||0!==u[2]){const e=vu;if(c){const t=wu;d.transformPoint3(h,c,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]+=u[0],e[1]+=u[1],e[2]+=u[2],f=N(A,e,Tu),I=gu,I[0]=a.eye[0]-e[0],I[1]=a.eye[1]-e[1],I[2]=a.eye[2]-e[2]}else f=A,I=a.eye;r.uniform3fv(this._uCameraEyeRtc,I),r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uWorldMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,f),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);const y=i._sectionPlanesState.sectionPlanes.length;if(y>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*y,a=n.renderFlags;for(let t=0;t<y;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Eu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(){const e=this._scene;e.canvas.gl,e.camera.project,this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesDataTextureOcclusionRenderer 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 sceneModelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),s.push("uniform highp sampler2D uTexturePerObjectMatrix;"),s.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),s.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),s.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),s.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),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("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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),s.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),s.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, 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 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),s.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, 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 (uObjectPerObjectColorsAndFlags, 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(sceneModelMatrix * objectDecodeAndInstanceMatrix) * 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*objectDecodeAndInstanceMatrix)) * 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 = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),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("flat in uint vFlags2;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (float(vFlags2) > 0.0);"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push(" if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Du=d.vec3(),Pu=d.vec3(),Ru=d.vec3(),Cu=d.vec3(),_u=d.mat4();class Bu{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a;if(!this._program&&(this._allocate(),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Du;if(I){const t=d.transformPoint3(h,c,Pu);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(i.viewMatrix,e,_u),f=Ru,f[0]=i.eye[0]-e[0],f[1]=i.eye[1]-e[1],f[2]=i.eye[2]-e[2]}else A=i.viewMatrix,f=i.eye;if(r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const m=n._sectionPlanesState.sectionPlanes.length;if(m>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,i=a.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Cu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t.camera.project;if(n.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState;e._lightsState;const s=t.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// Triangles dataTexture draw vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out highp vec2 vHighPrecisionZW;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("flat out uint vFlags2;")),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2.r;")),n.push("gl_Position = clipPos;"),n.push("vHighPrecisionZW = gl_Position.zw;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles dataTexture 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"),n.push("in highp vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ou=d.vec3(),Su=d.vec3(),Nu=d.vec3(),xu=d.vec3(),Lu=d.mat4();class Mu{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 n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:h}=n,p=a.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const I=0!==o[0]||0!==o[1]||0!==o[2],y=0!==c[0]||0!==c[1]||0!==c[2];if(I||y){const e=Ou;if(I){const t=Su;d.transformPoint3(u,o,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],A=N(p,e,Lu),f=Nu,f[0]=a.eye[0]-e[0],f[1]=a.eye[1]-e[1],f[2]=a.eye[2]-e[2]}else A=p,f=a.eye;r.uniform1i(this._uRenderPass,s),r.uniformMatrix4fv(this._uWorldMatrix,!1,h),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),r.uniformMatrix4fv(this._uViewNormalMatrix,!1,a.viewNormalMatrix),r.uniformMatrix4fv(this._uWorldNormalMatrix,!1,n.worldNormalMatrix);const m=i._sectionPlanesState.sectionPlanes.length;if(m>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,a=n.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const i=a.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,i?1:0),i){const s=e[t];if(o){const e=F(s.dist,s.dir,o,xu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.objectDecodeAndInstanceMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aNormal.bindArrayBuffer(l.normalsBuf),this._aColor.bindArrayBuffer(l.colorsBuf),this._aFlags.bindArrayBuffer(l.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(l.flags2Buf),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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("objectDecodeAndInstanceMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,s=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&ye.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 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),ye.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 * (objectDecodeAndInstanceMatrix * 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&&(ye.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,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&ye.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),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&&ye.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("void main(void) {"),s){n.push(" bool clippable = (float(vFlags2.x) > 0.0);"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&ye.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Fu=d.vec3(),Hu=d.vec3(),Uu=d.vec3(),Gu=d.vec3();d.vec4();const ju=d.mat4();class Vu{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 n=this._scene,i=n.camera,a=t.model,r=n.canvas.gl,l=t._state,o=l.textureState,c=t._state.origin,{position:u,rotationMatrix:h,rotationMatrixConjugate:p}=a;if(!this._program&&(this._allocate(),this.errors))return;let A,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,l)),o.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const I=0!==c[0]||0!==c[1]||0!==c[2],y=0!==u[0]||0!==u[1]||0!==u[2];if(I||y){const e=Fu;if(I){const t=d.transformPoint3(h,c,Hu);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=u[0],e[1]+=u[1],e[2]+=u[2],A=N(i.viewMatrix,e,ju),f=Uu,f[0]=i.eye[0]-e[0],f[1]=i.eye[1]-e[1],f[2]=i.eye[2]-e[2]}else A=i.viewMatrix,f=i.eye;if(r.uniform2fv(this._uPickClipPos,e.pickClipPos),r.uniform2f(this._uDrawingBufferSize,r.drawingBufferWidth,r.drawingBufferHeight),r.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),r.uniformMatrix4fv(this._uViewMatrix,!1,A),r.uniformMatrix4fv(this._uProjMatrix,!1,i.projMatrix),r.uniform3fv(this._uCameraEyeRtc,f),r.uniform1i(this._uRenderPass,s),n.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}const m=n._sectionPlanesState.sectionPlanes.length;if(m>0){const e=n._sectionPlanesState.sectionPlanes,s=t.layerIndex*m,i=a.renderFlags;for(let t=0;t<m;t++){const n=this._uSectionPlanes[t];if(n){const a=i.sectionPlanesActivePerLayer[s+t];if(r.uniform1i(n.active,a?1:0),a){const s=e[t];if(c){const e=F(s.dist,s.dir,c,Gu);r.uniform3fv(n.pos,e)}else r.uniform3fv(n.pos,s.pos);r.uniform3fv(n.dir,s.dir)}}}}l.numIndices8Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),r.drawArrays(r.TRIANGLES,0,l.numIndices8Bits)),l.numIndices16Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),r.drawArrays(r.TRIANGLES,0,l.numIndices16Bits)),l.numIndices32Bits>0&&(o.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),r.drawArrays(r.TRIANGLES,0,l.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Pe(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._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,n=e._sectionPlanesState.sectionPlanes.length;t<n;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t.camera.project;if(n.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState;e._lightsState;const s=t.sectionPlanes.length>0,n=[];return n.push("#version 300 es"),n.push("// trianglesDatatextureNormalsRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("uniform vec2 pickClipPos;"),n.push("uniform vec2 drawingBufferSize;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out vec4 vWorldPosition;"),s&&n.push("flat out uint vFlags2;"),n.push("void main(void) {"),n.push("int polygonIndex = gl_VertexID / 3;"),n.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.w) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n.push("vWorldPosition = worldPosition;"),s&&n.push("vFlags2 = flags2.r;"),n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// TrianglesDataTexturePickNormalsRenderer 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("in vec4 vWorldPosition;"),s){n.push("flat in uint vFlags2;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = vFlags2 > 0u;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ku{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 Mc(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Zc(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new iu(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Vu(this._scene)),this._vertexDepthRenderer||(this._vertexDepthRenderer=new hu(this._scene)),this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new mu(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _c(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _c(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Mc(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Bu(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Mu(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Vc(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Kc(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zc(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Vu(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Vu(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new iu(this._scene)),this._pickDepthRenderer}get vertexDepthRenderer(){return this._vertexDepthRenderer||(this._vertexDepthRenderer=new hu(this._scene)),this._vertexDepthRenderer}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new mu(this._scene)),this._snapDepthBufInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new bu(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 Qu={};class Wu{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class zu{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,s,n,i){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,s,2),this.texturePerObjectColorsAndFlags.bindTexture(e,n,3),this.texturePerObjectInstanceMatrices.bindTexture(e,i,4)}bindTriangleIndicesTextures(e,t,s,n){this.indicesPortionIdsPerBitnessTextures[n].bindTexture(e,t,5),this.indicesPerBitnessTextures[n].bindTexture(e,s,6)}bindEdgeIndicesTextures(e,t,s,n){this.edgeIndicesPortionIdsPerBitnessTextures[n].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[n].bindTexture(e,s,6)}}class Ku{constructor(e,t,s,n,i=null){this._gl=e,this._texture=t,this._textureWidth=s,this._textureHeight=n,this._textureData=i}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 Yu={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(Yu,null,4));let e=0;Object.keys(Yu).forEach((t=>{t.startsWith("size")&&(e+=Yu[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Yu.totalPolygons).toFixed(2)}`);let t={};Object.keys(Yu).forEach((s=>{s.startsWith("size")&&(t[s]=`${(Yu[s]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Xu{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,n,i,a,r){const l=t.length;this.numPortions=l;const o=4096,c=Math.ceil(l/512);if(0===c)throw"texture height===0";const u=new Uint8Array(16384*c);Yu.sizeDataColorsAndFlags+=u.byteLength,Yu.numberOfTextures++;for(let e=0;e<l;e++)u.set(t[e],32*e+0),u.set(s[e],32*e+4),u.set([0,0,0,0],32*e+8),u.set([0,0,0,0],32*e+12),u.set([n[e]>>24&255,n[e]>>16&255,n[e]>>8&255,255&n[e]],32*e+16),u.set([i[e]>>24&255,i[e]>>16&255,i[e]>>8&255,255&i[e]],32*e+20),u.set([a[e]>>24&255,a[e]>>16&255,a[e]>>8&255,255&a[e]],32*e+24),u.set([r[e]?1:0,0,0,0],32*e+28);const h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,c),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,c,e.RGBA_INTEGER,e.UNSIGNED_BYTE,u,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 Ku(e,h,o,c,u)}generateTextureForObjectOffsets(e,t){const s=512,n=Math.ceil(t/s);if(0===n)throw"texture height===0";const i=new Float32Array(1536*n).fill(0);Yu.sizeDataTextureOffsets+=i.byteLength,Yu.numberOfTextures++;const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,s,n),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,n,e.RGB,e.FLOAT,i,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 Ku(e,a,s,n,i)}generateTextureForInstancingMatrices(e,t){const s=t.length;if(0===s)throw"num instance matrices===0";const n=2048,i=Math.ceil(s/512),a=new Float32Array(8192*i);Yu.numberOfTextures++;for(let e=0;e<t.length;e++)a.set(t[e],16*e);const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGBA,e.FLOAT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i,a)}generateTextureForPositionsDecodeMatrices(e,t){const s=t.length;if(0===s)throw"num decode+entity matrices===0";const n=2048,i=Math.ceil(s/512),a=new Float32Array(8192*i);Yu.sizeDataPositionDecodeMatrices+=a.byteLength,Yu.numberOfTextures++;for(let e=0;e<t.length;e++)a.set(t[e],16*e);const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGBA,e.FLOAT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor8BitIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/3/n);if(0===i)throw"texture height===0";const a=new Uint8Array(n*i*3);Yu.sizeDataTextureIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGB_INTEGER,e.UNSIGNED_BYTE,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor16BitIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/3/n);if(0===i)throw"texture height===0";const a=new Uint16Array(n*i*3);Yu.sizeDataTextureIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGB_INTEGER,e.UNSIGNED_SHORT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor32BitIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/3/n);if(0===i)throw"texture height===0";const a=new Uint32Array(n*i*3);Yu.sizeDataTextureIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RGB_INTEGER,e.UNSIGNED_INT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor8BitsEdgeIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/2/n);if(0===i)throw"texture height===0";const a=new Uint8Array(n*i*2);Yu.sizeDataTextureEdgeIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RG_INTEGER,e.UNSIGNED_BYTE,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor16BitsEdgeIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/2/n);if(0===i)throw"texture height===0";const a=new Uint16Array(n*i*2);Yu.sizeDataTextureEdgeIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RG_INTEGER,e.UNSIGNED_SHORT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureFor32BitsEdgeIndices(e,t,s){if(0===s)return{texture:null,textureHeight:0};const n=4096,i=Math.ceil(s/2/n);if(0===i)throw"texture height===0";const a=new Uint32Array(n*i*2);Yu.sizeDataTextureEdgeIndices+=a.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];a.set(n,s),s+=n.length}const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RG_INTEGER,e.UNSIGNED_INT,a,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}generateTextureForPositions(e,t,s){const n=s/3,i=4096,a=Math.ceil(n/i);if(0===a)throw"texture height===0";const r=new Uint16Array(i*a*3);Yu.sizeDataTexturePositions+=r.byteLength,Yu.numberOfTextures++;for(let e=0,s=0,n=t.length;e<n;e++){const n=t[e];r.set(n,s),s+=n.length}const l=e.createTexture();return e.bindTexture(e.TEXTURE_2D,l),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,i,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,a,e.RGB_INTEGER,e.UNSIGNED_SHORT,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 Ku(e,l,i,a)}generateTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const s=t.length,n=4096,i=Math.ceil(s/n);if(0===i)throw"texture height===0";const a=new Uint16Array(n*i);a.set(t,0),Yu.sizeDataTexturePortionIds+=a.byteLength,Yu.numberOfTextures++;const r=e.createTexture();return e.bindTexture(e.TEXTURE_2D,r),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,n,i),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,i,e.RED_INTEGER,e.UNSIGNED_SHORT,a,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Ku(e,r,n,i)}}const qu=d.vec4([0,0,0,1]),Ju=d.vec4([0,0,0,1]);d.vec4([0,0,0,1]);const Zu=new Float32Array(16),$u=new Uint8Array(4),eh=new Float32Array(3),th=d.AABB3();let sh=0;const nh=d.identityMat4();class ih{constructor(e,t){Yu.numberOfLayers++,this._layerNumber=sh++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._dataTextureRenderers=function(e){const t=e.id;let s=Qu[t];return s||(s=new ku(e),Qu[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Qu[t],s._destroy()}))),s}(e.scene),this.model=e,this._buffer=new Wu,this._dataTextureState=new zu,this._dataTextureGenerator=new Xu,this._state=new Ke({origin:d.vec3(t.origin),metallicRoughnessBuf:null,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=d.collapseAABB3(),this._numUpdatesInFrame=0,this._finalized=!1}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&Yu.cannotCreatePortion.because10BitsObjectId++;let s=this._numPortions+t<=65536;const n=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[n]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let n=0,i=0;e.buckets.forEach((e=>{n+=e.positionsCompressed.length/3,i+=e.indices.length/3})),(this._state.numVertices+n>16777216||t+i>16777216)&&Yu.cannotCreatePortion.becauseTextureSize++,s&&=this._state.numVertices+n<=16777216&&t+i<=16777216}return s}createPortion(e){if(this._finalized)throw"Already finalized";const t=[],s=e.worldAABB;e.buckets.forEach(((n,i)=>{const a=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#${i}`:`${e.id}#${i}`;let r=this._bucketGeometries[a];r||(r=this._createBucketGeometry(e,n),this._bucketGeometries[a]=r);const l=d.collapseAABB3(th),o=this._createSubPortion(e,r,n,l);d.expandAABB3(s,l),t.push(o)}));const n=this._state.origin;0===n[0]&&0===n[1]&&0===n[2]||(s[0]+=n[0],s[1]+=n[1],s[2]+=n[2],s[3]+=n[0],s[4]+=n[1],s[5]+=n[2]),d.expandAABB3(this.aabb,s);const i=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(t),this.model.numPortions++,i}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Yu.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;Yu.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,n=t.indices,i=t.edgeIndices,a=this._buffer;a.positionsCompressed.push(s);const r=a.lenPositionsCompressed/3,l=s.length/3;let o;a.lenPositionsCompressed+=s.length;let c,u=0;if(n){let e;u=n.length/3,l<=256?(e=a.indices8Bits,o=a.lenIndices8Bits/3,a.lenIndices8Bits+=n.length):l<=65536?(e=a.indices16Bits,o=a.lenIndices16Bits/3,a.lenIndices16Bits+=n.length):(e=a.indices32Bits,o=a.lenIndices32Bits/3,a.lenIndices32Bits+=n.length),e.push(n)}let h=0;if(i){let e;h=i.length/2,l<=256?(e=a.edgeIndices8Bits,c=a.lenEdgeIndices8Bits/2,a.lenEdgeIndices8Bits+=i.length):l<=65536?(e=a.edgeIndices16Bits,c=a.lenEdgeIndices16Bits/2,a.lenEdgeIndices16Bits+=i.length):(e=a.edgeIndices32Bits,c=a.lenEdgeIndices32Bits/2,a.lenEdgeIndices32Bits+=i.length),e.push(i)}this._state.numVertices+=l,Yu.numberOfGeometries++;const p=d.collapseAABB3();d.expandAABB3Points3(p,t.positionsCompressed),Pt.decompressAABB(p,e.positionsDecodeMatrix);return{vertexBase:r,numVertices:l,numTriangles:u,numEdges:h,indicesBase:o,edgeIndicesBase:c,aabb:p,obb:null}}_createSubPortion(e,t,s,n){const i=e.color;e.metallic,e.roughness;const a=e.colors,r=e.opacity,l=e.meshMatrix,o=e.pickColor,c=this._buffer,u=this._state;if(c.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),c.perObjectInstancePositioningMatrices.push(l||nh),l){t.obb||(t.obb=d.AABB3ToOBB3(t.aabb));const e=t.obb;for(let t=0,s=e.length;t<s;t+=4)qu[0]=e[t+0],qu[1]=e[t+1],qu[2]=e[t+2],qu[3]=1,l&&d.transformPoint4(l,qu,Ju),d.expandAABB3Point3(n,Ju)}else d.expandAABB3(n,t.aabb);c.perObjectSolid.push(!!e.solid),a?c.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):i&&c.perObjectColors.push([i[0],i[1],i[2],r]),c.perObjectPickColors.push(o),c.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,c.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?u.numEdgeIndices8Bits:t.numVertices<=65536?u.numEdgeIndices16Bits:u.numEdgeIndices32Bits,c.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const h=this._subPortions.length;if(t.numTriangles>0){let e,s=3*t.numTriangles;t.numVertices<=256?(e=c.perTriangleNumberPortionId8Bits,u.numIndices8Bits+=s,Yu.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=c.perTriangleNumberPortionId16Bits,u.numIndices16Bits+=s,Yu.totalPolygons16Bits+=t.numTriangles):(e=c.perTriangleNumberPortionId32Bits,u.numIndices32Bits+=s,Yu.totalPolygons32Bits+=t.numTriangles),Yu.totalPolygons+=t.numTriangles;for(let s=0;s<t.numTriangles;s+=8)e.push(h)}if(t.numEdges>0){let e,s=2*t.numEdges;t.numVertices<=256?(e=c.perEdgeNumberPortionId8Bits,u.numEdgeIndices8Bits+=s,Yu.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=c.perEdgeNumberPortionId16Bits,u.numEdgeIndices16Bits+=s,Yu.totalEdges16Bits+=t.numEdges):(e=c.perEdgeNumberPortionId32Bits,u.numEdgeIndices32Bits+=s,Yu.totalEdges32Bits+=t.numEdges),Yu.totalEdges+=t.numEdges;for(let s=0;s<t.numEdges;s+=8)e.push(h)}return this._subPortions.push({numVertices:t.numTriangles}),this._numPortions++,Yu.numberOfPortions++,h}finalize(){if(this._finalized)return;const e=this._state,t=this._dataTextureState,s=this.model.scene.canvas.gl,n=this._buffer;e.gl=s,t.texturePerObjectColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(s,n.perObjectColors,n.perObjectPickColors,n.perObjectVertexBases,n.perObjectIndexBaseOffsets,n.perObjectEdgeIndexBaseOffsets,n.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dataTextureGenerator.generateTextureForInstancingMatrices(s,n.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(s,n.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(s,n.positionsCompressed,n.lenPositionsCompressed),t.texturePerPolygonIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perTriangleNumberPortionId32Bits),n.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perEdgeNumberPortionId8Bits)),n.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perEdgeNumberPortionId16Bits)),n.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(s,n.perEdgeNumberPortionId32Bits)),n.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,n.indices8Bits,n.lenIndices8Bits)),n.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,n.indices16Bits,n.lenIndices16Bits)),n.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,n.indices32Bits,n.lenIndices32Bits)),n.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitsEdgeIndices(s,n.edgeIndices8Bits,n.lenEdgeIndices8Bits)),n.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitsEdgeIndices(s,n.edgeIndices16Bits,n.lenEdgeIndices16Bits)),n.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitsEdgeIndices(s,n.edgeIndices32Bits,n.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,s){t&H&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&k&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&W&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&j&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&G&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&U&&(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&H?(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&Q?(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&k?(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&W?(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&z?(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&j?(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.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&U?(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&G?(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,n=s.length;e<n;e++)this._subPortionSetColor(s[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const s=this._dataTextureState,n=this.model.scene.canvas.gl;if($u[0]=t[0],$u[1]=t[1],$u[2]=t[2],$u[3]=t[3],s.texturePerObjectColorsAndFlags._textureData.set($u,32*e),this._deferredSetFlagsActive)return console.info("_subPortionSetColor defer"),void(this._deferredSetFlagsDirty=!0);++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,$u)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){const i=this._portionToSubPortionsMap[e];for(let e=0,a=i.length;e<a;e++)this._subPortionSetFlags(i[e],t,s,n)}_subPortionSetFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=!!(t&H),a=!!(t&k),r=!!(t&Q),l=!!(t&W),o=!!(t&U);let c,u;c=!i||o||a?sr.NOT_RENDERED:s?sr.COLOR_TRANSPARENT:sr.COLOR_OPAQUE,u=!i||o?sr.NOT_RENDERED:l?sr.SILHOUETTE_SELECTED:r?sr.SILHOUETTE_HIGHLIGHTED:a?sr.SILHOUETTE_XRAYED:sr.NOT_RENDERED;let h=0;h=!i||o?sr.NOT_RENDERED:l?sr.EDGES_SELECTED:r?sr.EDGES_HIGHLIGHTED:a?sr.EDGES_XRAYED:!!(t&z)?s?sr.EDGES_COLOR_TRANSPARENT:sr.EDGES_COLOR_OPAQUE:sr.NOT_RENDERED;let p=i&&!!(t&G)?sr.PICK:sr.NOT_RENDERED;const A=this._dataTextureState,d=this.model.scene.canvas.gl;$u[0]=c,$u[1]=u,$u[2]=h,$u[3]=p,A.texturePerObjectColorsAndFlags._textureData.set($u,32*e+8),this._deferredSetFlagsActive||n?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),d.bindTexture(d.TEXTURE_2D,A.texturePerObjectColorsAndFlags._texture),d.texSubImage2D(d.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,d.RGBA_INTEGER,d.UNSIGNED_BYTE,$u))}_setDeferredFlags(){}_setFlags2(e,t,s=!1){const n=this._portionToSubPortionsMap[e];for(let e=0,i=n.length;e<i;e++)this._subPortionSetFlags2(n[e],t,s)}_subPortionSetFlags2(e,t,s=!1){if(!this._finalized)throw"Not finalized";const n=t&j?255:0,i=this._dataTextureState,a=this.model.scene.canvas.gl;$u[0]=n,$u[1]=0,$u[2]=1,$u[3]=2,i.texturePerObjectColorsAndFlags._textureData.set($u,32*e+12),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),a.bindTexture(a.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),a.texSubImage2D(a.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,a.RGBA_INTEGER,a.UNSIGNED_BYTE,$u))}_setDeferredFlags2(){}setOffset(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,n=s.length;e<n;e++)this._subPortionSetOffset(s[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const s=this._dataTextureState,n=this.model.scene.canvas.gl;eh[0]=t[0],eh[1]=t[1],eh[2]=t[2],s.texturePerObjectOffsets._textureData.set(eh,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectOffsets._texture),n.texSubImage2D(n.TEXTURE_2D,0,0,e,1,1,n.RGB,n.FLOAT,eh))}setMatrix(e,t){const s=this._portionToSubPortionsMap[e];for(let e=0,n=s.length;e<n;e++)this._subPortionSetMatrix(s[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=this._dataTextureState,n=this.model.scene.canvas.gl;Zu.set(t),s.texturePerObjectInstanceMatrices._textureData.set(Zu,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectInstanceMatrices._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,n.RGBA,n.FLOAT,Zu))}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,sr.COLOR_OPAQUE):this._dataTextureRenderers.colorRenderer&&this._dataTextureRenderers.colorRenderer.drawLayer(t,this,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.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,sr.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,sr.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._dataTextureRenderers.edgesRenderer&&this._dataTextureRenderers.edgesRenderer.drawLayer(t,this,sr.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,sr.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,sr.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickMeshRenderer&&this._dataTextureRenderers.pickMeshRenderer.drawLayer(t,this,sr.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickDepthRenderer&&this._dataTextureRenderers.pickDepthRenderer.drawLayer(t,this,sr.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.snapDepthBufInitRenderer&&this._dataTextureRenderers.snapDepthBufInitRenderer.drawLayer(t,this,sr.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.vertexDepthRenderer&&this._dataTextureRenderers.vertexDepthRenderer.drawLayer(t,this,sr.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._dataTextureRenderers.pickNormalsRenderer&&this._dataTextureRenderers.pickNormalsRenderer.drawLayer(t,this,sr.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 ah=d.vec4(4),rh=d.vec4(),lh=d.vec4(),oh=d.vec3([1,0,0]),ch=d.vec3([0,1,0]),uh=d.vec3([0,0,1]);d.vec3(3),d.vec3(3);const hh=d.identityMat4();class ph{constructor(e){this._model=e.model,this.id=e.id,this._parentTransform=e.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=d.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=d.identityMat4(new Float32Array(16)),this._worldMatrix=d.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,e.matrix?this.matrix=e.matrix:(this.scale=e.scale,this.position=e.position,e.quaternion||(this.rotation=e.rotation)),e.parent&&e.parent._addChildTransform(this)}_addChildTransform(e){this._childTransforms.push(e),e._parentTransform=this,e._setWorldMatrixDirty(),e._setAABBDirty()}_addMesh(e){this._meshes.push(e),e.transform=this}get parentTransform(){return this._parentTransform}get meshes(){return this._meshes}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._model.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._model.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=d.identityMat4()),this._localMatrix.set(e||hh),d.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return ah[0]=e[0],ah[1]=e[1],ah[2]=e[2],ah[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(ah,rh),d.mulQuaternions(this.quaternion,rh,lh),this.quaternion=lh,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return ah[0]=e[0],ah[1]=e[1],ah[2]=e[2],ah[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(ah,rh),d.mulQuaternions(rh,this.quaternion,rh),this}rotateX(e){return this.rotate(oh,e)}rotateY(e){return this.rotate(ch,e)}rotateZ(e){return this.rotate(uh,e)}translate(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateX(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateY(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateZ(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._transformDirty()}_transformDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._childTransforms.length;e<t;e++){const t=this._childTransforms[e];if(t._transformDirty(),t._meshes&&t._meshes.length>0){const e=t._meshes;for(let t=0,s=e.length;t<s;t++)e[t]._transformDirty()}}if(this._meshes&&this._meshes.length>0){const e=this._meshes;for(let t=0,s=e.length;t<s;t++)e[t]._transformDirty()}}_buildWorldMatrix(){const e=this.matrix;if(this._parentTransform)d.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._childTransforms)for(let t=0,s=e._childTransforms.length;t<s;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}const Ah=d.vec3();d.mat4();const dh=d.vec3([1,1,1]),fh=d.vec3([0,0,0]),Ih=d.vec3([0,0,0]),yh=d.identityQuaternion(),mh=d.identityMat4(),vh=new Uint8Array([255,255,255]);class wh extends O{constructor(e,t={}){super(e,t),this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!1,this._vboBatchingLayerScratchMemory=(tr++,er),this._textureTranscoder=t.textureTranscoder||Ac(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=d.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._transforms={},this._meshes={},this._entities={},this._scheduledMeshes={},this.renderFlags=new Vn,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=d.vec3(t.origin||[0,0,0]),this._position=d.vec3(t.position||[0,0,0]),this._rotation=d.vec3(t.rotation||[0,0,0]),this._quaternion=d.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=d.vec4(t.quaternion||[0,0,0,1]),t.rotation&&d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=d.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=d.mat4(),this._worldRotationMatrixConjugate=d.mat4(),this._matrix=d.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=d.mat4(),d.inverseMat4(this._matrix,this._worldNormalMatrix),d.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=d.mat4(),this._viewNormalMatrix=d.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new sc({id:"defaultColorTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new sc({id:"defaultMetalRoughTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),s=new sc({id:"defaultNormalsTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),n=new sc({id:"defaultEmissiveTexture",texture:new Pi({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),i=new sc({id:"defaultOcclusionTexture",texture:new Pi({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=n,this._textures.defaultOcclusionTexture=i,this._textureSets.defaultTextureSet=new tc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:s,emissiveTexture:n,occlusionTexture:i})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||mh),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}get worldMatrix(){return this.matrix}get worldNormalMatrix(){return this._worldNormalMatrix}get viewMatrix(){return this._viewMatrix?(this._matrixDirty&&(this._rebuildMatrices(),this._viewMatrixDirty=!0),this._viewMatrixDirty&&(d.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}get viewNormalMatrix(){return this._viewNormalMatrix?(this._matrixDirty&&(this._rebuildMatrices(),this._viewMatrixDirty=!0),this._viewMatrixDirty&&(d.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}get backfaces(){return this._backfaces}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get entityList(){return this._entityList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){if(this._aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._entityList.length;e<t;e++)d.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}get visible(){return this.numVisibleLayerPortions>0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].visible=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].xrayed=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].highlighted=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].selected=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].edges=e;this.glRedraw()}get culled(){return this._culled}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].culled=e;this.glRedraw()}get clippable(){return this._clippable}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].clippable=e;this.glRedraw()}get collidable(){return this._collidable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].collidable=e}get pickable(){return this.numPickableLayerPortions>0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].pickable=e}get colorize(){return this._colorize}set colorize(e){this._colorize=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].colorize=e}get opacity(){return this._opacity}set opacity(e){this._opacity=e;for(let t=0,s=this._entityList.length;t<s;t++)this._entityList[t].opacity=e}get castsShadow(){return this._castsShadow}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get colorTextureEnabled(){return this._colorTextureEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}createQuantizationRange(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:Ur(e.aabb,d.mat4())}:this.error("[createQuantizationRange] Config missing: id")}createGeometry(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`[createGeometry] Param expected: indices (required for '${e.primitive}' primitive type)`),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Ur(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Hr(e.positions,t,e.positionsDecodeMatrix)}else e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed);if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,s=new Uint8Array(t.length);for(let e=0,n=t.length;e<n;e++)s[e]=255*t[e];e.colorsCompressed=s}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=vt(e.positions,e.indices,null,5):e.edgeIndices=vt(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets&&(this._dtxBuckets[e.id]=e.buckets),e.uv){const t=Pt.getUVBounds(e.uv),s=Pt.compressUVs(e.uv,t.min,t.max);e.uvCompressed=s.quantized,e.uvDecodeMatrix=s.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error(`[createGeometry] Unsupported value for 'primitive': '${e.primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);else this.error("[createGeometry] Config missing: id")}createTexture(e){const t=e.id;if(null==t)return void this.error("[createTexture] Config missing: id");if(this._textures[t])return void this.error("[createTexture] Texture already created: "+t);if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;let s=e.minFilter||1008;1006!==s&&1007!==s&&1008!==s&&1005!==s&&1004!==s&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),s=1008);let n=e.magFilter||1006;1006!==n&&1003!==n&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),n=1006);let i=e.wrapS||1e3;1001!==i&&1002!==i&&1e3!==i&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),i=1e3);let a=e.wrapT||1e3;1001!==a&&1002!==a&&1e3!==a&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),a=1e3);let r=e.wrapR||1e3;1001!==r&&1002!==r&&1e3!==r&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),r=1e3);let l=e.encoding||3e3;3e3!==l&&3001!==l&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),l=3e3);const o=new Pi({gl:this.scene.canvas.gl,minFilter:s,magFilter:n,wrapS:i,wrapT:a,wrapR:r,encoding:l});if(e.preloadColor&&o.setPreloadColor(e.preloadColor),e.image){const t=e.image;t.crossOrigin="Anonymous",o.setImage(t,{minFilter:s,magFilter:n,wrapS:i,wrapT:a,wrapR:r,flipY:e.flipY,encoding:l})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const c=new Image;c.onload=()=>{o.setImage(c,{minFilter:s,magFilter:n,wrapS:i,wrapT:a,wrapR:r,flipY:e.flipY,encoding:l}),this.glRedraw()},c.src=e.src;break;default:this._textureTranscoder?w.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],o).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,o).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 sc({id:t,texture:o})}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,n,i,a,r;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(n=this._textures[e.metallicRoughnessTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(i=this._textures[e.normalsTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(a=this._textures[e.emissiveTextureId],!a)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else a=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(r=this._textures[e.occlusionTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultOcclusionTexture;const l=new tc({id:t,model:this,colorTexture:s,metallicRoughnessTexture:n,normalsTexture:i,emissiveTexture:a,occlusionTexture:r});return this._textureSets[t]=l,l}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(this.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const s=new ph({id:e.id,model:this,parentTransform:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[s.id]=s,s}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?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position){const t=e.scale||dh,s=e.position||fh,n=e.rotation||Ih;d.eulerToQuaternion(n,"XYZ",yh),e.meshMatrix=d.composeMat4(s,yh,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Ur(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):vh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),s=[];L(e.positions,s,t)&&(e.positions=s,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Hr(e.positions,t,e.positionsDecodeMatrix)}e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=vt(e.positions,e.indices,null,2):e.edgeIndices=vt(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=gh(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=[];L(e.positions,t,Ah)&&(e.positions=t,e.origin=d.addVec3(e.origin,Ah,d.vec3()))}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=vt(e.positions,e.indices,null,2):e.edgeIndices=vt(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?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return void this.error(`[createMesh] Transform not found: ${e.transformId} - ensure that you create it first with createTransform()`)}else if(e.matrix)e.meshMatrix=e.matrix.slice();else{const t=e.scale||dh,s=e.position||fh,n=e.rotation||Ih;d.eulerToQuaternion(n,"XYZ",yh),e.meshMatrix=d.composeMat4(s,yh,t,d.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])]):vh,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=gh(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t,Eh(e)}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])]):vh,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]),Eh(e.geometry)}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createMesh(e){const t=new $a(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);const s=t.pickId,n=s>>24&255,i=s>>16&255,a=s>>8&255,r=255&s;switch(e.pickColor=new Uint8Array([r,a,i,n]),e.worldAABB=d.collapseAABB3(),e.aabb=e.worldAABB,e.solid="solid"===e.primitive,t.origin=d.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)}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(e),t.aabb=e.worldAABB,t.obb=e.obb||(e.geometry?e.geometry.obb:null),t.numPrimitives=e.numPrimitives,d.expandAABB3(this._aabb,t.aabb),this._meshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let s=0,n=e.buckets.length;s<n;s++)t+=e.buckets[s].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(let s=0,n=e.buckets.length;s<n;s++)t+=e.buckets[s].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:const s=e.geometry;t+=s.positions?s.positions.length:s.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(let s=0,n=e.buckets.length;s<n;s++)t+=e.buckets[s].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}_getDTXLayer(e){const t=e.origin,s=`${Math.round(t[0])}.${Math.round(t[1])}.${Math.round(t[2])}`;let n=this._dtxLayers[s];if(n){if(n.canCreatePortion(e))return n;n.finalize(),delete this._dtxLayers[s],n=null}return n=new ih(this,{layerIndex:0,origin:t}),this._dtxLayers[s]=n,this.layerList.push(n),n}_getVBOBatchingLayer(e){const t=this,s=e.origin,n=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",i=e.textureSetId||"-",a=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${e.primitive}.${n}.${i}`;let r=this._vboBatchingLayers[a];if(r)return r;let l=e.textureSet;for(;!r;){switch(e.primitive){case"triangles":case"solid":case"surface":r=new Al({model:t,textureSet:l,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:s,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0});break;case"lines":r=new Ao({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:s,maxGeometryBatchSize:this._maxGeometryBatchSize});break;case"points":r=new Ho({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:s,maxGeometryBatchSize:this._maxGeometryBatchSize})}const n=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?r.canCreatePortion(n):r.canCreatePortion(n,e.indices.length))||(r.finalize(),delete this._vboBatchingLayers[a],r=null)}return this._vboBatchingLayers[a]=r,this.layerList.push(r),r}_createHashStringFromMatrix(e){const t=e.join("");let s=0;for(let e=0;e<t.length;e++){s=(s<<5)-s+t.charCodeAt(e),s|=0}return(s>>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,s=e.origin,n=e.textureSetId||"-",i=e.geometryId,a=`${Math.round(s[0])}.${Math.round(s[1])}.${Math.round(s[2])}.${n}.${i}`;let r=this._vboInstancingLayers[a];if(r)return r;let l=e.textureSet;const o=e.geometry;for(;!r;)switch(o.primitive){case"triangles":case"surface":r=new ao({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0,solid:!1});break;case"solid":r=new ao({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0,solid:!0});break;case"lines":r=new Do({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0});break;case"points":r=new ec({model:t,textureSet:l,geometry:o,origin:s,layerIndex:0})}return this._vboInstancingLayers[a]=r,this.layerList.push(r),r}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=H),this._pickable&&!1!==e.pickable&&(t|=G),this._culled&&!1!==e.culled&&(t|=U),this._clippable&&!1!==e.clippable&&(t|=j),this._collidable&&!1!==e.collidable&&(t|=V),this._edges&&!1!==e.edges&&(t|=z),this._xrayed&&!1!==e.xrayed&&(t|=k),this._highlighted&&!1!==e.highlighted&&(t|=Q),this._selected&&!1!==e.selected&&(t|=W),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];const s=d.collapseAABB3();for(let n=0,i=e.meshIds.length;n<i;n++){const i=e.meshIds[n],a=this._meshes[i];a?a.parent?this.error(`Mesh with ID "${i}" already belongs to object with ID "${a.parent.id}" - ignoring this mesh`):(d.expandAABB3(s,a.aabb),t.push(a)):this.error(`Mesh with this ID not found: "${i}" - ignoring this mesh`)}const n=new X(this,e.isObject,e.id,t,e.flags,s,!0);this._entityList.push(n),this._entities[e.id]=n,this.numEntities++}finalize(){if(!this.destroyed){for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].finalize()}this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._dtxLayers={},this._vboInstancingLayers={},this._vboBatchingLayers={};for(let e=0,t=this._entityList.length;e<t;e++){this._entityList[e]._finalize()}for(let e=0,t=this._entityList.length;e<t;e++){this._entityList[e]._finalize2()}this.layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].layerIndex=e}this.glRedraw(),this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position}}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,s=this.layerList.length;t<s;t++){const s=this.layerList[t];this._getActiveSectionPlanesForLayer(s)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,s=this.scene._sectionPlanesState.sectionPlanes,n=s.length,i=e.layerIndex*n;if(n>0)for(let e=0;e<n;e++){s[e].active?(t.sectionPlanesActivePerLayer[i+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[i+e]=!1}return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawColorOpaque(t,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawShadow(t,e)}}setPickMatrices(e,t){if(0===this._numVisibleLayerPortions)return;const s=this.renderFlags;for(let n=0,i=s.visibleLayers.length;n<i;n++){const i=s.visibleLayers[n],a=this.layerList[i];a.setPickMatrices&&a.setPickMatrices(e,t)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s];this.layerList[n].drawPickNormals(t,e)}}drawSnapInitDepthBuf(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s],i=this.layerList[n];i.drawSnapInitDepthBuf&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,i.drawSnapInitDepthBuf(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}drawSnapDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let s=0,n=t.visibleLayers.length;s<n;s++){const n=t.visibleLayers[s],i=this.layerList[n];i.drawSnapDepths&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,i.drawSnapDepths(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}destroy(){for(let e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();this._vboBatchingLayers={};for(let e in this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(e)&&this._vboInstancingLayers[e].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(let e=0,t=this.layerList.length;e<t;e++)this.layerList[e].destroy();this.layerList=[];for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._destroy();this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==tr&&(tr--,0===tr&&er._clear()),super.destroy()}}function gh(e,t,s){let n,i,a,r;if(t||s?[n,i,a]=yc({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(n=e.positionsCompressed,i=e.indices,a=e.edgeIndices),s){r=Ec({positionsCompressed:n,indices:i,edgeIndices:a},n.length/3>65536?16:8)}else r=[{positionsCompressed:n,indices:i,edgeIndices:a}];return r}function Eh(e){if(e.obb=d.OBB3(),e.positionsCompressed&&e.positionsCompressed.length>0){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Pt.decompressAABB(t,e.positionsDecodeMatrix),d.AABB3ToOBB3(t,e.obb)}else if(e.positions&&e.positions.length>0){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positions),d.AABB3ToOBB3(t,e.obb)}else if(e.buckets){const t=d.collapseAABB3();for(let s=0,n=e.buckets.length;s<n;s++){const n=e.buckets[s];d.expandAABB3Points3(t,n.positionsCompressed)}Pt.decompressAABB(t,e.positionsDecodeMatrix),d.AABB3ToOBB3(t,e.obb)}}class Th extends wh{constructor(e,t={}){super(e,t)}}class bh extends O{constructor(e,t={}){super(e,t),this._skyboxMesh=new $n(this,{geometry:new _t(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new xt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Si(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class Dh{transcode(e,t,s={}){}destroy(){}}const Ph=d.vec4(),Rh=d.vec4(),Ch=d.vec3(),_h=d.vec3(),Bh=d.vec3(),Oh=d.vec4(),Sh=d.vec4(),Nh=d.vec4();class xh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,s){let n=!1;const i=this._scene.camera;if(e){const t=d.subVec3(e,i.eye,Ch);n=d.lenVec3(t)<s}if("perspective"===i.projection){i.ortho.scale=i.ortho.scale-s;const n=this._unproject(t,Oh),a=d.subVec3(n,i.eye,Nh),r=d.mulVec3Scalar(d.normalizeVec3(a),-s,[]);if(i.eye=[i.eye[0]-r[0],i.eye[1]-r[1],i.eye[2]-r[2]],i.look=[i.look[0]-r[0],i.look[1]-r[1],i.look[2]-r[2]],e){const t=d.subVec3(e,i.eye,Ch),s=d.lenVec3(t),n=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(i.look,i.eye,_h)),s);i.look=[i.eye[0]+n[0],i.eye[1]+n[1],i.eye[2]+n[2]]}}else if("ortho"===i.projection){const e=this._unproject(t,Oh);i.ortho.scale=i.ortho.scale-s,i.ortho._update();const n=this._unproject(t,Sh),a=d.subVec3(n,e,Nh),r=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(i.look,i.eye,Ch)),-s,_h),l=d.addVec3(a,r,Bh);i.eye=[i.eye[0]-l[0],i.eye[1]-l[1],i.eye[2]-l[2]],i.look=[i.look[0]-l[0],i.look[1]-l[1],i.look[2]-l[2]]}return n}_unproject(e,t){const s=this._scene.camera,n=s.project.transposedMatrix,i=n.subarray(8,12),a=n.subarray(12),r=[0,0,-1,1],l=d.dotVec4(r,i)/d.dotVec4(r,a);return s.project.unproject(e,l,Ph,Rh,t),t}destroy(){}}const Lh=d.vec3(),Mh=d.vec3(),Fh=d.vec3(),Hh=d.vec4(),Uh=d.vec4(),Gh=d.vec4();class jh{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=d.vec3(),this._cameraOffset=d.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=d.vec3(),this._rtcPos=d.vec3(),this._pivotViewPos=d.vec4(),this._pivotProjPos=d.vec4(),this._pivotCanvasPos=d.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const s=d.distVec3(t,e);let n=Math.tan(Math.PI/500)*s*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(n/=this._scene.camera.ortho.scale/2),x(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Mi(this._scene,si({radius:n})),this._pivotSphere=new $n(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const s=t.boundary,n=s[2],i=s[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*n/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*i/2);let a=t._lastBoundingClientRect;if(!a||t._canvasSizeChanged){const e=t.canvas;a=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(a.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(a.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),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new xt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const s=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,s),t=d.inverseMat4(t);const n=d.transformVec3(t,this._cameraOffset),i=d.vec3();if(d.subVec3(e.eye,s,i),d.addVec3(i,n),e.zUp){const e=i[1];i[1]=i[2],i[2]=e}this._radius=d.lenVec3(i),this._polar=Math.acos(i[1]/this._radius),this._azimuth=Math.atan2(i[0],i[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,Lh)),s=d.cross3Vec3(t,e.worldUp,Mh);return d.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(d.distVec3(this._scene.center,t.eye)),n=t.project.transposedMatrix,i=n.subarray(8,12),a=n.subarray(12),r=[0,0,-1,1],l=d.dotVec4(r,i)/d.dotVec4(r,a),o=Hh;t.project.unproject(e,l,Uh,Gh,o);const c=d.normalizeVec3(d.subVec3(o,t.eye,Lh)),u=d.addVec3(t.eye,d.mulVec3Scalar(c,s,Mh),Fh);this.setPivotPos(u)}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 n=-e;const i=-t;1===s.worldUp[2]&&(n=-n),this._azimuth+=.01*-n,this._polar+=.01*i,this._polar=d.clamp(this._polar,.001,Math.PI-.001);const a=[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=a[1];a[1]=a[2],a[2]=e}const r=d.lenVec3(d.subVec3(s.look,s.eye,d.vec3())),l=this.getPivotPos();d.addVec3(a,l);let o=d.lookAtMat4v(a,l,s.worldUp);o=d.inverseMat4(o);const c=d.transformVec3(o,this._cameraOffset);o[12]-=c[0],o[13]-=c[1],o[14]-=c[2];const u=[o[8],o[9],o[10]];s.eye=[o[12],o[13],o[14]],d.subVec3(s.eye,d.mulVec3Scalar(u,r),s.look),s.up=[o[4],o[5],o[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 Vh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._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 ve;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 kh=d.vec2();class Qh{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController;let r,l,o,c=0,u=0,h=0,p=0,A=!1;const f=d.vec3();let I=!0;const y=this._scene.canvas.canvas,m=[];function v(e=!0){y.style.cursor="move",c=n.pointerCanvasPos[0],u=n.pointerCanvasPos[1],h=n.pointerCanvasPos[0],p=n.pointerCanvasPos[1],e&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.picked&&a.pickedSurface&&a.pickResult&&a.pickResult.worldPos?(A=!0,f.set(a.pickResult.worldPos)):A=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const n=t.keyCode;m[n]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;const n=t.keyCode;m[n]=!1}),y.addEventListener("mousedown",this._mouseDownHandler=t=>{if(s.active&&s.pointerEnabled)switch(t.which){case 1:m[e.input.KEY_SHIFT]||s.planView?(r=!0,v()):(r=!0,v(!1));break;case 2:l=!0,v();break;case 3:o=!0,s.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!s.active||!s.pointerEnabled)return;if(!r&&!l&&!o)return;const t=e.canvas.boundary,a=t[2],h=t[3],p=n.pointerCanvasPos[0],I=n.pointerCanvasPos[1];if(m[e.input.KEY_SHIFT]||s.planView||!s.panRightClick&&l||s.panRightClick&&o){const t=p-c,s=I-u,n=e.camera;if("perspective"===n.projection){const a=Math.abs(A?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(n.perspective.fov/2*Math.PI/180);i.panDeltaX+=1.5*t*a/h,i.panDeltaY+=1.5*s*a/h}else i.panDeltaX+=.5*n.ortho.scale*(t/h),i.panDeltaY+=.5*n.ortho.scale*(s/h)}else!r||l||o||s.planView||(s.firstPerson?(i.rotateDeltaY-=(p-c)/a*s.dragRotationRate/2,i.rotateDeltaX+=(I-u)/h*(s.dragRotationRate/4)):(i.rotateDeltaY-=(p-c)/a*(1.5*s.dragRotationRate),i.rotateDeltaX+=(I-u)/h*(1.5*s.dragRotationRate)));c=p,u=I}),y.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{s.active&&s.pointerEnabled&&n.mouseover&&(I=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:r=!1,l=!1,o=!1}}),y.addEventListener("mouseup",this._mouseUpHandler=e=>{if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){let s=e.target,n=0,i=0,a=0,r=0;for(;s.offsetParent;)n+=s.offsetLeft,i+=s.offsetTop,a+=s.scrollLeft,r+=s.scrollTop,s=s.offsetParent;t[0]=e.pageX+a-n,t[1]=e.pageY+r-i}else e=window.event,t[0]=e.x,t[1]=e.y}(e,kh);const s=kh[0],n=kh[1];Math.abs(s-h)<3&&Math.abs(n-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:kh,event:e},!0)}y.style.removeProperty("cursor")}}),y.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.active&&s.pointerEnabled});const w=1/60;let g=null;y.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=performance.now()/1e3;var a=null!==g?t-g:0;g=t,a>.05&&(a=.05),a<w&&(a=w);const r=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===r)return;const l=r/Math.abs(r);i.dollyDelta+=-l*a*s.mouseWheelDollyRate,I&&(n.followPointerDirty=!0,I=!1)},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const Wh=d.vec3(),zh=d.vec3(),Kh=d.vec3(),Yh=d.vec3(),Xh=d.vec3(),qh={eye:d.vec3(),look:d.vec3(),up:d.vec3()};class Jh{constructor(e,t,s,n){this._scene=e;const i=t.cameraControl,a=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!n.mouseover)return;const r=i._isKeyDownForAction(i.AXIS_VIEW_RIGHT),l=i._isKeyDownForAction(i.AXIS_VIEW_BACK),o=i._isKeyDownForAction(i.AXIS_VIEW_LEFT),c=i._isKeyDownForAction(i.AXIS_VIEW_FRONT),u=i._isKeyDownForAction(i.AXIS_VIEW_TOP),h=i._isKeyDownForAction(i.AXIS_VIEW_BOTTOM);if(!(r||l||o||c||u||h))return;const p=e.aabb,A=d.getAABB3Diag(p);d.getAABB3Center(p,Wh);const f=Math.abs(A/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),I=1.1*A;qh.orthoScale=I,r?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldRight,f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):l?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldForward,f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):o?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldRight,-f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):c?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldForward,-f,zh),Xh)),qh.look.set(Wh),qh.up.set(a.worldUp)):u?(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldUp,f,zh),Xh)),qh.look.set(Wh),qh.up.set(d.normalizeVec3(d.mulVec3Scalar(a.worldForward,1,Kh),Yh))):h&&(qh.eye.set(d.addVec3(Wh,d.mulVec3Scalar(a.worldUp,-f,zh),Xh)),qh.look.set(Wh),qh.up.set(d.normalizeVec3(d.mulVec3Scalar(a.worldForward,-1,Kh)))),!s.firstPerson&&s.followPointer&&t.pivotController.setPivotPos(Wh),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 Zh{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController,r=t.pivotController,l=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let o=!1,c=!1;const u=this._scene.canvas.canvas,h=s=>{let n;s&&s.worldPos&&(n=s.worldPos);const i=s&&s.entity?s.entity.aabb:e.aabb;if(n){const s=e.camera;d.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:i})}else t.cameraFlight.flyTo({aabb:i})};u.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(o||c)return;const i=l.hasSubs("hover"),r=l.hasSubs("hoverEnter"),u=l.hasSubs("hoverOut"),h=l.hasSubs("hoverOff"),p=l.hasSubs("hoverSurface"),A=l.hasSubs("hoverSnapOrSurface");if(i||r||u||h||p||A)if(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=p,a.scheduleSnapOrPick=A,a.update(),a.pickResult){if(a.pickResult.entity){const t=a.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&l.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),l.fire("hoverEnter",a.pickResult,!0),this._lastPickedEntityId=t)}l.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&l.fire("hoverSurface",a.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(l.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),l.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}),u.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(o=!0),3===t.which&&(c=!0);if(1===t.which&&s.active&&s.pointerEnabled&&(n.mouseDownClientX=t.clientX,n.mouseDownClientY=t.clientY,n.mouseDownCursorX=n.pointerCanvasPos[0],n.mouseDownCursorY=n.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===t.which))){const t=a.pickResult;t&&t.worldPos?(r.setPivotPos(t.worldPos),r.startPivot()):(s.smartPivot?r.setCanvasPivotPos(n.pointerCanvasPos):r.setPivotPos(e.camera.look),r.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(o=!1),3===e.which&&(c=!1),r.getPivoting()&&r.endPivot()}),u.addEventListener("mouseup",this._canvasMouseUpHandler=i=>{if(!s.active||!s.pointerEnabled)return;if(!(1===i.which))return;if(r.hidePivot(),Math.abs(i.clientX-n.mouseDownClientX)>3||Math.abs(i.clientY-n.mouseDownClientY)>3)return;const o=l.hasSubs("picked"),c=l.hasSubs("pickedNothing"),u=l.hasSubs("pickedSurface"),p=l.hasSubs("doublePicked"),A=l.hasSubs("doublePickedSurface"),f=l.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||p||A||f))return(o||c||u)&&(a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=u,a.update(),a.pickResult?(l.fire("picked",a.pickResult,!0),a.pickedSurface&&l.fire("pickedSurface",a.pickResult,!0)):l.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo,a.schedulePickSurface=u,a.update();const e=a.pickResult,i=a.pickedSurface;this._timeout=setTimeout((()=>{e?(l.fire("picked",e,!0),i&&(l.fire("pickedSurface",e,!0),!s.firstPerson&&s.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):l.fire("pickedNothing",{canvasPos:n.pointerCanvasPos},!0),this._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),a.pickCursorPos=n.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo||p||A,a.schedulePickSurface=a.schedulePickEntity&&A,a.update(),a.pickResult){if(l.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult,!0),s.doublePickFlyTo&&(h(a.pickResult),!s.firstPerson&&s.followPointer)){const e=a.pickResult.entity.aabb,s=d.getAABB3Center(e);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(l.fire("doublePickedNothing",{canvasPos:n.pointerCanvasPos},!0),s.doublePickFlyTo&&(h(),!s.firstPerson&&s.followPointer)){const s=e.aabb,n=d.getAABB3Center(s);t.pivotController.setPivotPos(n),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 $h{constructor(e,t,s,n,i){this._scene=e;const a=e.input,r=[],l=e.canvas.canvas;let o=!0;this._onSceneMouseMove=a.on("mousemove",(()=>{o=!0})),this._onSceneKeyDown=a.on("keydown",(t=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&n.mouseover&&(r[t]=!0,t===a.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=a.on("keyup",(n=>{s.active&&s.pointerEnabled&&e.input.keyboardEnabled&&(r[n]=!1,n===a.KEY_SHIFT&&(l.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(l=>{if(!s.active||!s.pointerEnabled||!e.input.keyboardEnabled)return;if(!n.mouseover)return;const c=t.cameraControl,u=l.deltaTime/1e3;if(!s.planView){const e=c._isKeyDownForAction(c.ROTATE_Y_POS,r),n=c._isKeyDownForAction(c.ROTATE_Y_NEG,r),a=c._isKeyDownForAction(c.ROTATE_X_POS,r),l=c._isKeyDownForAction(c.ROTATE_X_NEG,r),o=u*s.keyboardRotationRate;(e||n||a||l)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),e?i.rotateDeltaY+=o:n&&(i.rotateDeltaY-=o),a?i.rotateDeltaX+=o:l&&(i.rotateDeltaX-=o),!s.firstPerson&&s.followPointer&&t.pivotController.startPivot())}if(!r[a.KEY_CTRL]&&!r[a.KEY_ALT]){const e=c._isKeyDownForAction(c.DOLLY_BACKWARDS,r),a=c._isKeyDownForAction(c.DOLLY_FORWARDS,r);if(e||a){const r=u*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),a?i.dollyDelta-=r:e&&(i.dollyDelta+=r),o&&(n.followPointerDirty=!0,o=!1)}}const h=c._isKeyDownForAction(c.PAN_FORWARDS,r),p=c._isKeyDownForAction(c.PAN_BACKWARDS,r),A=c._isKeyDownForAction(c.PAN_LEFT,r),d=c._isKeyDownForAction(c.PAN_RIGHT,r),f=c._isKeyDownForAction(c.PAN_UP,r),I=c._isKeyDownForAction(c.PAN_DOWN,r),y=(r[a.KEY_ALT]?.3:1)*u*s.keyboardPanRate;(h||p||A||d||f||I)&&(!s.firstPerson&&s.followPointer&&t.pivotController.startPivot(),I?i.panDeltaY+=y:f&&(i.panDeltaY+=-y),d?i.panDeltaX+=-y:A&&(i.panDeltaX+=y),p?i.panDeltaZ+=y:h&&(i.panDeltaZ+=-y))}))}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 ep=d.vec3();class tp{constructor(e,t,s,n,i){this._scene=e;const a=e.camera,r=t.pickController,l=t.pivotController,o=t.panController;let c=1,u=1,h=null;this._onTick=e.on("tick",(()=>{if(!s.active||!s.pointerEnabled)return;let t="default";if(Math.abs(i.dollyDelta)<.001&&(i.dollyDelta=0),Math.abs(i.rotateDeltaX)<.001&&(i.rotateDeltaX=0),Math.abs(i.rotateDeltaY)<.001&&(i.rotateDeltaY=0),0===i.rotateDeltaX&&0===i.rotateDeltaY||(i.dollyDelta=0),s.followPointer&&--c<=0&&(c=1,0!==i.dollyDelta)){if(0===i.rotateDeltaY&&0===i.rotateDeltaX&&s.followPointer&&n.followPointerDirty&&(r.pickCursorPos=n.pointerCanvasPos,r.schedulePickSurface=!0,r.update(),r.pickResult&&r.pickResult.worldPos?h=r.pickResult.worldPos:(u=1,h=null),n.followPointerDirty=!1),h){const t=Math.abs(d.lenVec3(d.subVec3(h,e.camera.eye,ep)));u=t/s.dollyProximityThreshold}u<s.dollyMinSpeed&&(u=s.dollyMinSpeed)}const p=i.dollyDelta*u;if(0===i.rotateDeltaY&&0===i.rotateDeltaX||(!s.firstPerson&&s.followPointer&&l.getPivoting()?(l.continuePivot(i.rotateDeltaY,i.rotateDeltaX),l.showPivot()):(0!==i.rotateDeltaX&&(s.firstPerson?a.pitch(-i.rotateDeltaX):a.orbitPitch(i.rotateDeltaX)),0!==i.rotateDeltaY&&(s.firstPerson?a.yaw(i.rotateDeltaY):a.orbitYaw(i.rotateDeltaY))),i.rotateDeltaX*=s.rotationInertia,i.rotateDeltaY*=s.rotationInertia,t="grabbing"),Math.abs(i.panDeltaX)<.001&&(i.panDeltaX=0),Math.abs(i.panDeltaY)<.001&&(i.panDeltaY=0),Math.abs(i.panDeltaZ)<.001&&(i.panDeltaZ=0),0!==i.panDeltaX||0!==i.panDeltaY||0!==i.panDeltaZ){const e=d.vec3();let n,r;if(e[0]=i.panDeltaX,e[1]=i.panDeltaY,e[2]=i.panDeltaZ,s.constrainVertical){a.xUp?(n=a.eye[0],r=a.look[0]):a.yUp?(n=a.eye[1],r=a.look[1]):a.zUp&&(n=a.eye[2],r=a.look[2]),a.pan(e);const t=a.eye,s=a.look;a.xUp?(t[0]=n,s[0]=r):a.yUp?(t[1]=n,s[1]=r):a.zUp&&(t[2]=n,s[2]=r),a.eye=t,a.look=s}else a.pan(e);t="grabbing"}if(i.panDeltaX*=s.panInertia,i.panDeltaY*=s.panInertia,i.panDeltaZ*=s.panInertia,0!==p){if(t=p<0?"zoom-in":"zoom-out",s.firstPerson){let e,t;if(s.constrainVertical&&(a.xUp?(e=a.eye[0],t=a.look[0]):a.yUp?(e=a.eye[1],t=a.look[1]):a.zUp&&(e=a.eye[2],t=a.look[2])),s.followPointer){o.dollyToCanvasPos(h,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0)}else a.pan([0,0,p]),a.ortho.scale=a.ortho.scale-p;if(s.constrainVertical){const s=a.eye,n=a.look;a.xUp?(s[0]=e,n[0]=t):a.yUp?(s[1]=e,n[1]=t):a.zUp&&(s[2]=e,n[2]=t),a.eye=s,a.look=n}}else if(s.planView)if(s.followPointer){o.dollyToCanvasPos(h,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0)}else a.ortho.scale=a.ortho.scale+p,a.zoom(p);else if(s.followPointer){o.dollyToCanvasPos(h,n.pointerCanvasPos,-p)&&(n.followPointerDirty=!0)}else a.ortho.scale=a.ortho.scale+p,a.zoom(p);i.dollyDelta*=s.dollyInertia}r.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class sp{constructor(e,t,s,n,i){this._scene=e;const a=this._scene.canvas.canvas;a.addEventListener("mouseenter",this._mouseEnterHandler=()=>{n.mouseover=!0}),a.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{n.mouseover=!1,a.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{np(e,a,n.pointerCanvasPos)}),a.addEventListener("mousedown",this._mouseDownHandler=e=>{s.active&&s.pointerEnabled&&(np(e,a,n.pointerCanvasPos),n.mouseover=!0)}),a.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 np(e,t,s){if(e){const{x:n,y:i}=t.getBoundingClientRect();s[0]=e.clientX-n,s[1]=e.clientY-i}else e=window.event,s[0]=e.x,s[1]=e.y;return s}const ip=function(e,t){if(e){let s=e.target,n=0,i=0;for(;s.offsetParent;)n+=s.offsetLeft,i+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-n,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class ap{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController,r=t.pivotController,l=d.vec2(),o=d.vec2(),c=d.vec2(),u=d.vec2(),h=[],p=this._scene.canvas.canvas;let A=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 i=t.touches,o=t.changedTouches;for(n.touchStartTime=Date.now(),1===i.length&&1===o.length&&(ip(i[0],l),s.followPointer&&(a.pickCursorPos=l,a.schedulePickSurface=!0,a.update(),s.planView||(a.picked&&a.pickedSurface&&a.pickResult&&a.pickResult.worldPos?(r.setPivotPos(a.pickResult.worldPos),!s.firstPerson&&r.startPivot()&&r.showPivot()):(s.smartPivot?r.setCanvasPivotPos(n.pointerCanvasPos):r.setPivotPos(e.camera.look),!s.firstPerson&&r.startPivot()&&r.showPivot()))));h.length<i.length;)h.push(d.vec2());for(let e=0,t=i.length;e<t;++e)ip(i[e],h[e]);A=i.length}),p.addEventListener("touchend",this._canvasTouchEndHandler=()=>{r.getPivoting()&&r.endPivot()}),p.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!s.active||!s.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const r=e.canvas.boundary,l=r[2],p=r[3],I=t.touches;if(t.touches.length===A){if(1===A){ip(I[0],o),d.subVec2(o,h[0],u);const t=u[0],a=u[1];if(null!==n.longTouchTimeout&&(Math.abs(t)>s.longTapRadius||Math.abs(a)>s.longTapRadius)&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),s.planView){const n=e.camera;if("perspective"===n.projection){const r=Math.abs(e.camera.eyeLookDist)*Math.tan(n.perspective.fov/2*Math.PI/180);i.panDeltaX+=t*r/p*s.touchPanRate,i.panDeltaY+=a*r/p*s.touchPanRate}else i.panDeltaX+=.5*n.ortho.scale*(t/p)*s.touchPanRate,i.panDeltaY+=.5*n.ortho.scale*(a/p)*s.touchPanRate}else i.rotateDeltaY-=t/l*(1*s.dragRotationRate),i.rotateDeltaX+=a/p*(1.5*s.dragRotationRate)}else if(2===A){const t=I[0],r=I[1];ip(t,o),ip(r,c);const l=d.geometricMeanVec2(h[0],h[1]),u=d.geometricMeanVec2(o,c),A=d.vec2();d.subVec2(l,u,A);const f=A[0],y=A[1],m=e.camera,v=d.distVec2([t.pageX,t.pageY],[r.pageX,r.pageY]),w=(d.distVec2(h[0],h[1])-v)*s.touchDollyRate;if(i.dollyDelta=w,Math.abs(w)<1)if("perspective"===m.projection){const t=a.pickResult?a.pickResult.worldPos:e.center,n=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(m.perspective.fov/2*Math.PI/180);i.panDeltaX-=f*n/p*s.touchPanRate,i.panDeltaY-=y*n/p*s.touchPanRate}else i.panDeltaX-=.5*m.ortho.scale*(f/p)*s.touchPanRate,i.panDeltaY-=.5*m.ortho.scale*(y/p)*s.touchPanRate;n.pointerCanvasPos=u}for(let e=0;e<A;++e)ip(I[e],h[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}const rp=function(e,t){if(e){let s=e.target,n=0,i=0;for(;s.offsetParent;)n+=s.offsetLeft,i+=s.offsetTop,s=s.offsetParent;t[0]=e.pageX-n,t[1]=e.pageY-i}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class lp{constructor(e,t,s,n,i){this._scene=e;const a=t.pickController,r=t.cameraControl;let l;const o=[],c=new Float32Array(2);let u=-1,h=-1;const p=this._scene.canvas.canvas,A=s=>{let n;s&&s.worldPos&&(n=s.worldPos);const i=s?s.entity.aabb:e.aabb;if(n){const s=e.camera;d.subVec3(s.eye,s.look,[]),t.cameraFlight.flyTo({aabb:i})}else t.cameraFlight.flyTo({aabb:i})};p.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!s.active||!s.pointerEnabled)return;null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null);const i=e.touches,a=e.changedTouches;if(l=Date.now(),1===i.length&&1===a.length){u=l,rp(i[0],c);const a=c[0],r=c[1],o=i[0].pageX,h=i[0].pageY;n.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(o),Math.round(h)],canvasPos:[Math.round(a),Math.round(r)],event:e},!0),n.longTouchTimeout=null}),s.longTapTimeout)}else u=-1;for(;o.length<i.length;)o.push(new Float32Array(2));for(let e=0,t=i.length;e<t;++e)rp(i[e],o[e]);o.length=i.length},{passive:!0}),p.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!s.active||!s.pointerEnabled)return;const t=Date.now(),i=e.touches,l=e.changedTouches,p=r.hasSubs("pickedSurface");null!==n.longTouchTimeout&&(clearTimeout(n.longTouchTimeout),n.longTouchTimeout=null),0===i.length&&1===l.length&&u>-1&&t-u<150&&(h>-1&&u-h<325?(rp(l[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=p,a.update(),a.pickResult?(a.pickResult.touchInput=!0,r.fire("doublePicked",a.pickResult),a.pickedSurface&&r.fire("doublePickedSurface",a.pickResult),s.doublePickFlyTo&&A(a.pickResult)):(r.fire("doublePickedNothing"),s.doublePickFlyTo&&A()),h=-1):d.distVec2(o[0],c)<4&&(rp(l[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=p,a.update(),a.pickResult?(a.pickResult.touchInput=!0,r.fire("picked",a.pickResult),a.pickedSurface&&r.fire("pickedSurface",a.pickResult)):r.fire("pickedNothing"),h=t),u=-1),o.length=i.length;for(let e=0,t=i.length;e<t;++e)o[e][0]=i[e].pageX,o[e][1]=i[e].pageY},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class op extends O{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const s=this.scene;this._controllers={cameraControl:this,pickController:new Vh(this,this._configs),pivotController:new jh(s,this._configs),panController:new xh(s),cameraFlight:new Ca(this,{duration:.5})},this._handlers=[new sp(this.scene,this._controllers,this._configs,this._states,this._updates),new ap(this.scene,this._controllers,this._configs,this._states,this._updates),new Qh(this.scene,this._controllers,this._configs,this._states,this._updates),new Jh(this.scene,this._controllers,this._configs,this._states,this._updates),new Zh(this.scene,this._controllers,this._configs,this._states,this._updates),new lp(this.scene,this._controllers,this._configs,this._states,this._updates),new $h(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new tp(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",w.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,n=s.length;e<n;e++){if(t[s[e]])return!0}return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}get active(){return this._configs.active}set snapToVertex(e){this._configs.snapToVertex=!!e}get snapToVertex(){return this._configs.snapToVertex}set snapToEdge(e){this._configs.snapToEdge=!!e}get snapToEdge(){return this._configs.snapToEdge}set snapRadius(e){e=e||30,this._configs.snapRadius=e}get snapRadius(){return this._configs.snapRadius}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}enablePivotSphere(e={}){this._controllers.pivotController.enablePivotSphere(e)}disablePivotSphere(){this._controllers.pivotController.disablePivotSphere()}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}set doubleClickTimeFrame(e){this._configs.doubleClickTimeFrame=null!=e?e:250}get doubleClickTimeFrame(){return this._configs.doubleClickTimeFrame}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class cp{constructor(e,t,s,n,i){this.name=e,this.type=s,this.value=t,this.valueType=n,this.description=i}}class up{constructor(e){if(this.id=e.id,this.originalSystemId=e.originalSystemId,this.metaModels=[],this.name=e.name,this.type=e.type,this.properties=[],e.properties){const t=e.properties;for(let e=0,s=t.length;e<s;e++){const s=t[e];this.properties.push(new cp(s.name,s.value,s.type,s.valueType,s.description))}}}}class hp{constructor(e){this.metaModels=[],this.id=e.id,this.parentId=e.parentId,this.parent=null,this.originalSystemId=e.originalSystemId,this.name=e.name,this.type=e.type,this.propertySetIds=e.propertySetIds,this.propertySets=[],this.attributes=e.attributes||{},void 0!==e.external&&null!==e.external&&(this.external=e.external)}get metaModel(){return 1==this.metaModels.length?this.metaModels[0]:null}getObjectIDsInSubtree(){const e=[];return function t(s){if(!s)return;e.push(s.id);const n=s.children;if(n)for(var i=0,a=n.length;i<a;i++)t(n[i])}(this),e}withMetaObjectsInSubtree(e){!function t(s){if(!s)return;e(s);const n=s.children;if(n)for(var i=0,a=n.length;i<a;i++)t(n[i])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var s=0,n=e.length;s<n;s++)t[e[s]]=e[s];const i=[];return function e(s){if(!s)return;t[s.type]&&i.push(s.id);const n=s.children;if(n)for(var a=0,r=n.length;a<r;a++)e(n[a])}(this),i}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class pp{constructor(e){this.id=e.id,this.projectId=e.projectId,this.revisionId=e.revisionId,this.author=e.author,this.createdAt=e.createdAt,this.creatingApplication=e.creatingApplication,this.schema=e.schema,this.metaScene=e.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects=[],this.graph=e.graph||{},this.metaScene.metaModels[this.id]=this,this.finalized=!1}get rootMetaObject(){return 1==this.rootMetaObjects.length?this.rootMetaObjects[0]:null}loadData(e,t={}){if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);const s=this.metaScene,n=e.properties;if(e.propertySets)for(let t=0,i=e.propertySets.length;t<i;t++){const i=e.propertySets[t];let a=s.propertySets[i.id];a||(n&&this._decompressProperties(n,i.properties),a=new up({id:i.id,originalSystemId:i.originalSystemId||i.id,type:i.type,name:i.name,properties:i.properties}),s.propertySets[a.id]=a),a.metaModels.push(this),this.propertySets.push(a)}if(e.metaObjects)for(let t=0,n=e.metaObjects.length;t<n;t++){const n=e.metaObjects[t],i=n.id;let a=s.metaObjects[i];if(!a){const e=n.type,t=n.originalSystemId,s=n.propertySets||n.propertySetIds;a=new hp({id:i,originalSystemId:t,parentId:n.parent,type:e,name:n.name,attributes:n.attributes,propertySetIds:s,external:n.external}),this.metaScene.metaObjects[i]=a}a.metaModels.push(this),n.parent||(this.rootMetaObjects.push(a),s.rootMetaObjects[i]=a),this.metaObjects.push(a)}}_decompressProperties(e,t){for(let s=0,n=t.length;s<n;s++){const n=t[s];if(Number.isInteger(n)){const i=e[n];i&&(t[s]=i)}}}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const s=e.metaObjects[t];if(s.children&&(s.children=[]),s.propertySets&&(s.propertySets=[]),s.propertySetIds)for(let t=0,n=s.propertySetIds.length;t<n;t++){const n=s.propertySetIds[t],i=e.propertySets[n];s.propertySets.push(i)}}for(let t in e.metaObjects){const s=e.metaObjects[t];if(s.parentId){const t=e.metaObjects[s.parentId];t&&(s.parent=t,(t.children||(t.children=[])).push(s))}}e.metaObjectsByType={};for(let t in e.metaObjects){const s=e.metaObjects[t],n=s.type;(e.metaObjectsByType[n]||(e.metaObjectsByType[n]={}))[t]=s}this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}getJSON(){const e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]};for(let t=0,s=this.metaObjects.length;t<s;t++){const s=this.metaObjects[t],n={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name};s.parent&&(n.parent=s.parent.id),s.attributes&&(n.attributes=s.attributes),s.propertySetIds&&(n.propertySetIds=s.propertySetIds),e.metaObjects.push(n)}for(let t=0,s=this.propertySets.length;t<s;t++){const s=this.propertySets[t],n={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name,propertyies:[]};for(let e=0,t=s.properties.length;e<t;e++){const t=s.properties[e],i={id:t.id,description:t.description,type:t.type,name:t.name,value:t.value,valueType:t.valueType};n.properties.push(i)}e.propertySets.push(n)}return e}_globalizeIDs(e,t){const s=!!t.globalizeObjectIds;if(e.metaObjects)for(let t=0,n=e.metaObjects.length;t<n;t++){const n=e.metaObjects[t];if(n.originalSystemId=n.id,n.parent&&(n.originalParentSystemId=n.parent),s&&(n.id=d.globalizeObjectId(this.id,n.id),n.parent&&(n.parent=d.globalizeObjectId(this.id,n.parent))),s){const e=n.propertySetIds;if(e){const t=[];for(let s=0,n=e.length;s<n;s++)t.push(d.globalizeObjectId(this.id,e[s]));n.propertySetIds=t,n.originalSystemPropertySetIds=e}}else n.originalSystemPropertySetIds=n.propertySetIds}if(e.propertySets)for(let t=0,n=e.propertySets.length;t<n;t++){const n=e.propertySets[t];n.originalSystemId=n.id,s&&(n.id=d.globalizeObjectId(this.id,n.id))}}}class Ap{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}on(e,t){let 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,n=s.length;e<n;e++)s[e](t)}off(e){}createMetaModel(e,t,s={}){const n=new pp({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return n.loadData(t),n.finalize(),n}destroyMetaModel(e){const t=this.metaModels[e];if(t){if(t.propertySets)for(let s=0,n=t.propertySets.length;s<n;s++){const n=t.propertySets[s];if(1===n.metaModels.length)delete this.propertySets[n.id];else{const t=[];for(let s=0,i=n.metaModels.length;s<i;s++)n.metaModels[s].id!==e&&t.push(n.metaModels[s]);n.metaModels=t}}if(t.metaObjects)for(let e=0,s=t.metaObjects.length;e<s;e++){const s=t.metaObjects[e];s.type;const n=s.id;if(1===s.metaModels.length)delete this.metaObjects[n],s.parent||delete this.rootMetaObjects[n];else{const e=[],n=t.id;for(let t=0,i=s.metaModels.length;t<i;t++)s.metaModels[t].id!==n&&e.push(s.metaModels[t]);s.metaModels=e}}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.children&&(t.children=[]),t.propertySets&&(t.propertySets=[]),t.propertySetIds)for(let e=0,s=t.propertySetIds.length;e<s;e++){const s=t.propertySetIds[e],n=this.propertySets[s];t.propertySets.push(n)}}this.metaObjectsByType={};for(let e in this.metaObjects){const t=this.metaObjects[e],s=t.type;t.children&&(t.children=null),(this.metaObjectsByType[s]||(this.metaObjectsByType[s]={}))[e]=t}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.parentId){const e=this.metaObjects[t.parentId];e&&(t.parent=e,(e.children||(e.children=[])).push(t))}}delete this.metaModels[e],this.fire("metaModelDestroyed",e)}}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,s){const n=[],i=this.metaObjects[e],a=t&&t.length>0?dp(t):null,r=s&&s.length>0?dp(s):null,l=e=>{if(!e)return;var t=!0;(r&&r[e.type]||a&&!a[e.type])&&(t=!1),t&&n.push(e.id);const s=e.children;if(s)for(var i=0,o=s.length;i<o;i++)l(s[i])};return l(i),n}withMetaObjectsInSubtree(e,t){const s=this.metaObjects[e];s&&s.withMetaObjectsInSubtree(t)}}function dp(e){const t={};for(var s=0,n=e.length;s<n;s++)t[e[s]]=!0;return t}
|
|
18
18
|
/*!
|
|
19
19
|
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
20
20
|
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|