@xeokit/xeokit-sdk 2.4.0-alpha-71 → 2.4.0-alpha-72

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.
@@ -7,7 +7,7 @@ class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){
7
7
  * @author https://github.com/tmarti, with support from https://tribia.com/
8
8
  * @license MIT
9
9
  */
10
- function is(e,t){t.length;const s=e.length,n=[],i=[],a=e=>{for(let s=0,n=e.meshIds.length;s<n;s++)if(t[e.meshIds[s]].geometryId)return!0;return!1};for(let r=0;r<s;r++){const s=e[r];if(a(s)){i.push(r);continue}const l=p.collapseAABB3();let o=0;s.meshIds.forEach((e=>{const s=t[e];let n,i;if(s.positionsCompressed){const e=bt.getPositionsBounds(s.positionsCompressed);n=bt.decompressPosition(e.min,s.positionsDecodeMatrix,[]),i=bt.decompressPosition(e.max,s.positionsDecodeMatrix,[])}else{const e=bt.getPositionsBounds(s.positions);n=e.min,i=e.max}n[0]+=s.origin[0],n[1]+=s.origin[1],n[2]+=s.origin[2],i[0]+=s.origin[0],i[1]+=s.origin[1],i[2]+=s.origin[2],p.expandAABB3Point3(l,n),p.expandAABB3Point3(l,i),o+=s.numPrimitives})),n[r]={aabb:l,numPrimitives:o,entityId:s.id}}let r,l=[],o={};if(Object.keys(n).length>0){r=function(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=e[s];n&&t.push({minX:n.aabb[0],minY:n.aabb[1],minZ:n.aabb[2],maxX:n.aabb[3],maxY:n.aabb[4],maxZ:n.aabb[5],entity:{id:s,xeokitId:n.entityId,meshes:[{numPrimitives:n.numPrimitives}]},numPrimitives:n.numPrimitives})}const s=new ss(4);return s.load(t),s}(n);let e=ns({aabbTree:r});l=e.orderedEntityIds,o=e.clusteringResult.entityIdToClusterIdMapping}return{orderedClusteredIndexes:l,entityIdToClusterIdMapping:o,instancedIndexes:i,rTreeBasedAabbTree:r}}const as=p.vec3(),rs=180/Math.PI,ls=new Float32Array(262144);for(let e=-256;e<256;e++)for(let t=-256;t<256;t++){const s=(e+256<<9)+(t+256),n=Math.max(Math.abs(e),Math.abs(t));ls[s]=Math.atan2(e/n,t/n)}function os(e,t){const s=256/Math.max(Math.abs(e),Math.abs(t)),n=Math.round(e*s)+255,i=Math.round(t*s)+255;return ls[(n<<9)+i]}class cs{constructor(){this._aabbTree=null,this._orderedMeshList=[],this._orderedEntityList=[],this._frustumProps={dirty:!0,wMultiply:1,hMultiply:1},this._cullFrame=0,this.finalized=!1}initializeVFCState(e,t){if(this.finalized)throw"Already finalized";const s=is(e,t);this._aabbTree=s.rTreeBasedAabbTree;for(let n=0,i=s.orderedClusteredIndexes.length;n<i;n++){const i=s.orderedClusteredIndexes[n],a=s.entityIdToClusterIdMapping[i],r=e[i],l=[];for(let e=0,s=r.meshIds.length;e<s;e++){const s=r.meshIds[e];t[s].id=this._orderedMeshList.length,l.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:a,mesh:t[s]})}r.meshIds=l,this._orderedEntityList.push(r)}for(let n=0,i=s.instancedIndexes.length;n<i;n++){let i=e[s.instancedIndexes[n]];const a=[];for(let e=0,s=i.meshIds.length;e<s;e++){const s=i.meshIds[e];t[s].id=this._orderedMeshList.length,a.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:99999,mesh:t[s]})}i.meshIds=a,this._orderedEntityList.push(i)}}finalize(e,t){if(this.finalized)throw"Already finalized";let s=-1;for(let n=0,i=this._orderedMeshList.length;n<i;n++){const{clusterNumber:i,mesh:a}=this._orderedMeshList[n];-1!==s&&s!==i&&t.call(e),e._createMesh(a),s=i}for(let t=0,s=this._orderedEntityList.length;t<s;t++)e._createEntity(this._orderedEntityList[t]);this._orderedMeshList=[],this._orderedEntityList=[],this.finalized=!0}applyViewFrustumCulling(e){if(!this.finalized)throw"Not finalized";if(!this._aabbTree)return;this._canvasElement||(this._canvasElement=e.scene.canvas.canvas),this._camera||(this._camera=e.scene.camera),this._ensureFrustumPropsUpdated(e),this._initializeCullingDataIfNeeded(e);const t=this._searchVisibleNodesWithFrustumCulling();this._cullFrame++,this._markVisibleFrameOfVisibleNodes(t,this._cullFrame),this._cullNonVisibleNodes(e,this._cullFrame)}_initializeCullingDataIfNeeded(e){if(this._internalNodesList)return;if(!this._aabbTree)return;const t=this._aabbTree.all();let s=0;t.forEach((e=>{s=Math.max(s,e.entity.id)}));const n=new Array(s+1);t.forEach((t=>{n[t.entity.id]=e.objects[t.entity.xeokitId]})),this._internalNodesList=n,this._lastVisibleFrameOfNodes=new Array(n.length),this._lastVisibleFrameOfNodes.fill(0)}_searchVisibleNodesWithFrustumCulling(){return this._aabbTree.searchCustom(((e,t)=>this._aabbIntersectsCameraFrustum(e,t)),(e=>this._aabbContainedInCameraFrustum(e)))}_markVisibleFrameOfVisibleNodes(e,t){const s=this._lastVisibleFrameOfNodes;for(let n=0,i=e.length;n<i;n++)s[e[n].entity.id]=t}_cullNonVisibleNodes(e,t){const s=this._internalNodesList,n=this._lastVisibleFrameOfNodes;for(let e=0,i=s.length;e<i;e++)s[e]&&(s[e].culledVFC=n[e]!==t)}_getPointsForBBox(e){const t=[];for(let s=0;s<8;s++)t.push(new Float32Array([1&s?e.maxX:e.minX,2&s?e.maxY:e.minY,4&s?e.maxZ:e.minZ]));return t}_aabbIntersectsCameraFrustum(e,t){if(t)return!0;if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const s=this._aabbIntersectsCameraFrustum_internal(e);return!!((4096&s||!(1&s||2&s)||1&s)&&(8192&s||!(16&s||32&s)||16&s)&&(16384&s||!(256&s||512&s)||256&s))}_aabbContainedInCameraFrustum(e){if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const t=e._check;return 1&t&&16&t&&256&t}_ensureFrustumPropsUpdated(e){const t=Math.min(this._canvasElement.width,this._canvasElement.height);this._frustumProps.wMultiply=this._canvasElement.width/t,this._frustumProps.hMultiply=this._canvasElement.height/t;const s=this._canvasElement.width/this._canvasElement.height;let n=this._camera.perspective.fov;s<1&&(n/=s),n=Math.min(n,120),this._frustumProps.fov=n;const i=p.inverseMat4(e.worldMatrix,p.mat4()),a=p.transformVec3(i,this._camera.eye,[0,0,0]),r=p.transformVec3(i,this._camera.look,[0,0,0]);this._frustumProps.forward=p.normalizeVec3(p.subVec3(r,a,[0,0,0]),[0,0,0]),this._frustumProps.up=p.normalizeVec3(this._camera.up,[0,0,0]),this._frustumProps.right=p.normalizeVec3(p.cross3Vec3(this._frustumProps.forward,this._frustumProps.up,[0,0,0]),[0,0,0]),this._frustumProps.eye=a.slice(),this._frustumProps.CAM_FACTOR_1=this._frustumProps.fov/2*this._frustumProps.wMultiply/rs,this._frustumProps.CAM_FACTOR_2=this._frustumProps.fov/2*this._frustumProps.hMultiply/rs}_aabbIntersectsCameraFrustum_internal(e){const t=e._points||this._getPointsForBBox(e);e._points=t;let s=819;for(let e=0,n=t.length;e<n;e++){const n=t[e],i=as;i[0]=n[0]-this._frustumProps.eye[0],i[1]=n[1]-this._frustumProps.eye[1],i[2]=n[2]-this._frustumProps.eye[2];const a=p.dotVec3(i,this._frustumProps.forward);a<0?(s|=4,s&=-2):(s|=8,s&=-3);const r=os(p.dotVec3(i,this._frustumProps.right),a);Math.abs(r)>this._frustumProps.CAM_FACTOR_1?(s|=r<0?64:128,s&=-17):s&=-33;const l=os(p.dotVec3(i,this._frustumProps.up),a);Math.abs(l)>this._frustumProps.CAM_FACTOR_2?(s|=l<0?1024:2048,s&=-257):s&=-513}return 4&s&&8&s&&(s|=4096),64&s&&128&s&&(s|=8192),1024&s&&2048&s&&(s|=16384),e._check=s,s}}class us{constructor(e,t){this.sceneModel=t,this.entities=[],this.meshes=[],this.finalized=!1}addEntity(e){if(this.finalized)throw"Already finalized";this.entities.push(e)}addMesh(e){if(this.finalized)throw"Already finalized";this.meshes.push(e)}finalize(e){if(this.finalized)throw"Already finalized";this.finalized=!0,this.VFCState=new cs,this.VFCState.initializeVFCState(this.entities,this.meshes),this.VFCState.finalize(this.sceneModel,e),this._onSceneRendering=this.sceneModel.scene.on("rendering",(()=>this.applyViewFrustumCulling.call(this)))}applyViewFrustumCulling(){this.finalized&&this.VFCState.applyViewFrustumCulling(this.sceneModel)}destroy(){this.finalized&&this.sceneModel.off(this._onSceneRendering)}}class hs extends _{constructor(e,t={}){super(e,t),this._scene=e,this._vfcManagers={},this._vfcManagerList=[],this.enabled=t.enabled,this._init()}_init(){this._scene.on("rendering",(()=>{for(let e=0,t=this._vfcManagerList.length;e<t;e++)this._vfcManagerList[e].applyViewFrustumCulling()}))}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}getVFCManager(e){const t=new us(this.scene,e);return this._vfcManagers[t.id]=t,this._vfcManagerList=Object.values(this._vfcManagers),t}putVFCManager(e){delete this._vfcManagers[e.id],this._vfcManagerList=Object.values(this._vfcManagers)}destroy(){super.destroy()}}function ps(e,t){const s={};let n,i;for(let a=0,r=t.length;a<r;a++)n=t[a],i=e.component[n],i?i.isEntity?s[n]=!0:e.warn("pick(): Component is not an Entity: "+n):e.warn("pick(): Component not found: "+n);return s}class As extends _{get type(){return"Scene"}constructor(e,t={}){super(null,t);const s=t.canvasElement||document.getElementById(t.canvasId);if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";const n=!!t.transparent,i=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new fe(this,{dontClear:!0,canvas:s,spinnerElementId:t.spinnerElementId,transparent:n,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new je(this,{transparent:n,alphaDepthMask:i}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,n=t.length;e<n;e++)s.push("cp");return s.push(";"),e=s.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let s=0,n=this.sectionPlanes.length;s<n;s++)if(this.sectionPlanes[s].id===t.id)return this.sectionPlanes.splice(s,1),void(e=null)}},this._lightsState=new function(){const e=p.vec4([0,0,0,0]),t=p.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,n=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let n;for(let s=0,i=t.length;s<i;s++)n=t[s],e.push("/"),e.push(n.type),e.push("world"===n.space?"w":"v"),n.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),n=null,s=null},this.removeLight=function(e){for(let t=0,i=this.lights.length;t<i;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),n&&n.id===e.id&&(n=null),void(s=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),s=null},this.removeReflectionMap=function(e){for(let t=0,n=this.reflectionMaps.length;t<n;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(s=null)},this.addLightMap=function(e){this.lightMaps.push(e),s=null},this.removeLightMap=function(e){for(let t=0,n=this.lightMaps.length;t<n;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(s=null)},this.getAmbientColorAndIntensity=function(){if(!n)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){n=t;break}}if(n){const e=n.color,s=n.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=s,t}return e}},this.input=new ke(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new Ht(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Ut(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,R._addScene(this),this._initDefaults(),this._viewport=new ze(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new pt(this,{id:"default.camera",dontClear:!0}),new ft(this,{color:[1,1,1],intensity:.7}),new dt(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new dt(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()})),this.lod=new $t(this,{enabled:t.lodEnabled}),this.vfc=new hs(this,{enabled:t.vfcEnabled})}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+m.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=p.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const n=this.types[s];n&&(delete n[t],m.isEmptyObject(n)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&R.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,n=this._clearEachPass;let i,a;for(i=0;i<s;i++)t.pass=i,this.fire("rendering",t,!0),a=n||0===i,this._renderer.render({pass:i,clear:a,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=p.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||Ct(Rt)}get material(){return this.components["default.material"]||new St(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new xt(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new xt(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new xt(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new Mt(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Vt(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new kt(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=p.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=p.AABB3());let e,t=p.MAX_DOUBLE,s=p.MAX_DOUBLE,n=p.MAX_DOUBLE,i=p.MIN_DOUBLE,a=p.MIN_DOUBLE,r=p.MIN_DOUBLE;const l=this._collidables;let o,c=!1;for(const u in l)if(l.hasOwnProperty(u)){if(o=l[u],!1===o.collidable)continue;e=o.aabb,e[0]<t&&(t=e[0]),e[1]<s&&(s=e[1]),e[2]<n&&(n=e[2]),e[3]>i&&(i=e[3]),e[4]>a&&(a=e[4]),e[5]>r&&(r=e[5]),c=!0}c||(t=-100,s=-100,n=-100,i=100,a=100,r=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=n,this._aabb[3]=i,this._aabb[4]=a,this._aabb[5]=r,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const s=e.includeEntities||e.include;s&&(e.includeEntityIds=ps(this,s));const n=e.excludeEntities||e.exclude;return n&&(e.excludeEntityIds=ps(this,n)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapMode||"vertex")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t<s;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,s=e.length;t<s;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,s=e.length;t<s;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,s=e.length;t<s;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(m.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,s=p.MAX_DOUBLE,n=p.MAX_DOUBLE,i=p.MAX_DOUBLE,a=p.MIN_DOUBLE,r=p.MIN_DOUBLE,l=p.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const o=e.aabb;o[0]<s&&(s=o[0]),o[1]<n&&(n=o[1]),o[2]<i&&(i=o[2]),o[3]>a&&(a=o[3]),o[4]>r&&(r=o[4]),o[5]>l&&(l=o[5]),t=!0}})),t){const e=p.AABB3();return e[0]=s,e[1]=n,e[2]=i,e[3]=a,e[4]=r,e[5]=l,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){m.isString(e)&&(e=[e]);let s=!1;for(let n=0,i=e.length;n<i;n++){const i=e[n];let a=this.objects[i];if(a)s=t(a)||s;else{const e=this.modelIds;for(let n=0,r=e.length;n<r;n++){const r=e[n],l=p.globalizeObjectId(r,i);a=this.objects[l],a&&(s=t(a)||s)}}}return s}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ds=1e3,fs=1001,Is=1002,ys=1003,ms=1004,vs=1004,ws=1005,gs=1005,Ts=1006,Es=1007,bs=1007,Ds=1008,Ps=1008,Rs=1009,Cs=1010,_s=1011,Bs=1012,Os=1013,Ss=1014,Ns=1015,xs=1016,Ls=1017,Ms=1018,Fs=1020,Hs=1021,Us=1022,Gs=1023,Vs=1024,js=1025,ks=1026,Qs=1027,Ws=1028,zs=1029,Ks=1030,Ys=1031,Xs=1033,qs=33776,Js=33777,Zs=33778,$s=33779,en=35840,tn=35841,sn=35842,nn=35843,an=36196,rn=37492,ln=37496,on=37808,cn=37809,un=37810,hn=37811,pn=37812,An=37813,dn=37814,fn=37815,In=37816,yn=37817,mn=37818,vn=37819,wn=37820,gn=37821,Tn=36492,En=3e3,bn=3001,Dn=1e4,Pn=10001,Rn=10002,Cn=10003,_n=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene._lightsState,i=e._geometry._state,a=e._state.billboard,r=e._state.stationary,l=s.sectionPlanes.length>0,o=!!i.compressGeometry,c=[];c.push("#version 300 es"),c.push("// Lambertian drawing vertex shader"),c.push("in vec3 position;"),c.push("uniform mat4 modelMatrix;"),c.push("uniform mat4 viewMatrix;"),c.push("uniform mat4 projMatrix;"),c.push("uniform vec4 colorize;"),c.push("uniform vec3 offset;"),o&&c.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(c.push("uniform float logDepthBufFC;"),c.push("out float vFragDepth;"),c.push("bool isPerspectiveMatrix(mat4 m) {"),c.push(" return (m[2][3] == - 1.0);"),c.push("}"),c.push("out float isPerspective;"));l&&c.push("out vec4 vWorldPosition;");if(c.push("uniform vec4 lightAmbient;"),c.push("uniform vec4 materialColor;"),c.push("uniform vec3 materialEmissive;"),i.normalsBuf){c.push("in vec3 normal;"),c.push("uniform mat4 modelNormalMatrix;"),c.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(c.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&c.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&c.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(c.push("uniform vec3 lightPos"+e+";"),c.push("uniform vec3 lightDir"+e+";")))}o&&(c.push("vec3 octDecode(vec2 oct) {"),c.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),c.push(" if (v.z < 0.0) {"),c.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);"),c.push(" }"),c.push(" return normalize(v);"),c.push("}"))}c.push("out vec4 vColor;"),"points"===i.primitiveName&&c.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(c.push("void billboard(inout mat4 mat) {"),c.push(" mat[0][0] = 1.0;"),c.push(" mat[0][1] = 0.0;"),c.push(" mat[0][2] = 0.0;"),"spherical"===a&&(c.push(" mat[1][0] = 0.0;"),c.push(" mat[1][1] = 1.0;"),c.push(" mat[1][2] = 0.0;")),c.push(" mat[2][0] = 0.0;"),c.push(" mat[2][1] = 0.0;"),c.push(" mat[2][2] =1.0;"),c.push("}"));c.push("void main(void) {"),c.push("vec4 localPosition = vec4(position, 1.0); "),c.push("vec4 worldPosition;"),o&&c.push("localPosition = positionsDecodeMatrix * localPosition;");i.normalsBuf&&(o?c.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):c.push("vec4 localNormal = vec4(normal, 0.0); "),c.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),c.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));c.push("mat4 viewMatrix2 = viewMatrix;"),c.push("mat4 modelMatrix2 = modelMatrix;"),r&&c.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===a||"cylindrical"===a?(c.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),c.push("billboard(modelMatrix2);"),c.push("billboard(viewMatrix2);"),c.push("billboard(modelViewMatrix);"),i.normalsBuf&&(c.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),c.push("billboard(modelNormalMatrix2);"),c.push("billboard(viewNormalMatrix2);"),c.push("billboard(modelViewNormalMatrix);")),c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i.normalsBuf&&c.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(c.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),c.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),c.push("float lambertian = 1.0;"),i.normalsBuf)for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?c.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):c.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}c.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),c.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}c.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),l&&c.push("vWorldPosition = worldPosition;");"points"===i.primitiveName&&c.push("gl_PointSize = pointSize;");c.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(c.push("vFragDepth = 1.0 + clipPos.w;"),c.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return c.push("gl_Position = clipPos;"),c.push("}"),c}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState;e._material._state;const n=e._geometry._state,i=s.sectionPlanes.length>0,a=t.gammaOutput,r=[];r.push("#version 300 es"),r.push("// Lambertian drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(i){r.push("in vec4 vWorldPosition;"),r.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}r.push("in vec4 vColor;"),a&&(r.push("uniform float gammaFactor;"),r.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}"));if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}"points"===n.primitiveName&&(r.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push("float r = dot(cxy, cxy);"),r.push("if (r > 1.0) {"),r.push(" discard;"),r.push("}"));t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");a?r.push("outColor = linearToGamma(vColor, gammaFactor);"):r.push("outColor = vColor;");return r.push("}"),r}(e)):(this.vertex=function(e){const t=e.scene;e._material;const s=e._state,n=t._sectionPlanesState,i=e._geometry._state,a=t._lightsState;let r;const l=s.billboard,o=s.background,c=s.stationary,u=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=Sn(e),p=n.sectionPlanes.length>0,A=On(e),d=!!i.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),p&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));a.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===r.type&&"view"===r.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));d&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.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);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}u&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&f.push("uniform mat3 uvDecodeMatrix;"));i.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===i.primitiveName&&f.push("uniform float pointSize;");"spherical"!==l&&"cylindrical"!==l||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===l&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),d&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(d?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),c?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):o&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&"world"===r.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===r.type&&("world"===r.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}u&&(d?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));i.colors&&f.push("vColor = color;");"points"===i.primitiveName&&f.push("gl_PointSize = pointSize;");p&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));o&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=e._material,n=e._geometry._state,i=e.scene._sectionPlanesState,a=e.scene._lightsState,r=e._material._state,l=i.sectionPlanes.length>0,o=Sn(e),c=n.uvBuf,u="PhongMaterial"===r.type,h="MetallicMaterial"===r.type,p="SpecularMaterial"===r.type,A=On(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));A&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(l){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var I=0;I<i.sectionPlanes.length;I++)f.push("uniform bool sectionPlaneActive"+I+";"),f.push("uniform vec3 sectionPlanePos"+I+";"),f.push("uniform vec3 sectionPlaneDir"+I+";")}o&&(a.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),u&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Bn[a.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||p)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),a.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Bn[a.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),n.colors&&f.push("in vec4 vColor;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");o&&(a.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));r.ambient&&f.push("uniform vec3 materialAmbient;");r.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==r.alpha&&null!==r.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");r.emissive&&f.push("uniform vec3 materialEmissive;");r.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==r.glossiness&&null!==r.glossiness&&f.push("uniform float materialGlossiness;");void 0!==r.shininess&&null!==r.shininess&&f.push("uniform float materialShininess;");r.specular&&f.push("uniform vec3 materialSpecular;");void 0!==r.metallic&&null!==r.metallic&&f.push("uniform float materialMetallic;");void 0!==r.roughness&&null!==r.roughness&&f.push("uniform float materialRoughness;");void 0!==r.specularF0&&null!==r.specularF0&&f.push("uniform float materialSpecularF0;");c&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));c&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));c&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));c&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));o&&c&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));o&&c&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));o&&c&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));o&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));c&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));c&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));o&&c&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));o&&c&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));o&&c&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));o&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),o)for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(A)for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),l){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(I=0;I<i.sectionPlanes.length;I++)f.push("if (sectionPlaneActive"+I+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+I+".xyz, vWorldPosition.xyz - sectionPlanePos"+I+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===n.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),r.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");r.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):r.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");n.colors&&f.push("diffuseColor *= vColor.rgb;");r.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");r.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==r.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");n.colors&&f.push("alpha *= vColor.a;");void 0!==r.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==r.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==r.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==r.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));c&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Bn[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));c&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Bn[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));c&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Bn[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));c&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Bn[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));c&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));c&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(o&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){c&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),u&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),p&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),u&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||h)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),A&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),u&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}u?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),d&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},Bn={};function On(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,s=t.length;e<s;e++)if(t[e].castsShadow)return!0;return!1}function Sn(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}Bn[3e3]="linearToLinear",Bn[3001]="sRGBToLinear";const Nn=p.vec3(),xn=new e({}),Ln=function(e,t){this.id=xn.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new _n(t),this._allocate(t)},Mn={};Ln.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let n=Mn[s];if(!n){if(n=new Ln(s,e),n.errors)return console.log(n.errors.join("\n")),null;Mn[s]=n,d.memory.programs++}return n._useCount++,n},Ln.prototype.put=function(){0==--this._useCount&&(xn.removeItem(this.id),this._program&&this._program.destroy(),delete Mn[this._hash],d.memory.programs--)},Ln.prototype.webglContextRestored=function(){this._program=null},Ln.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=pe.MAX_TEXTURE_UNITS,n=t.scene,i=t._material,a=n.canvas.gl,r=this._program,l=t._state,o=t._material._state,c=t._geometry._state,u=n.camera,h=t.origin,p=l.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,p&&a.depthFunc(a.LEQUAL),this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(l.originHash,h):u.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,u.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,h?L(n.dist,n.dir,h,Nn):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(o.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=o.backfaces;e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t);const n=o.frontface;switch(e.frontface!==n&&(n?a.frontFace(a.CCW):a.frontFace(a.CW),e.frontface=n),e.lineWidth!==o.lineWidth&&(a.lineWidth(o.lineWidth),e.lineWidth=o.lineWidth),this._uPointSize&&a.uniform1f(this._uPointSize,o.pointSize),o.type){case"LambertMaterial":this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialColor&&a.uniform4f(this._uMaterialColor,o.color[0],o.color[1],o.color[2],o.alpha),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive);break;case"PhongMaterial":this._uMaterialShininess&&a.uniform1f(this._uMaterialShininess,o.shininess),this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0),i._ambientMap&&i._ambientMap._state.texture&&this._uMaterialAmbientMap&&(r.bindTexture(this._uMaterialAmbientMap,i._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMaterialAmbientMapMatrix&&a.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,i._ambientMap._state.matrix)),i._diffuseMap&&i._diffuseMap._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,i._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,i._diffuseMap._state.matrix)),i._specularMap&&i._specularMap._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,i._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,i._specularMap._state.matrix)),i._emissiveMap&&i._emissiveMap._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,i._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,i._emissiveMap._state.matrix)),i._alphaMap&&i._alphaMap._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,i._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,i._alphaMap._state.matrix)),i._reflectivityMap&&i._reflectivityMap._state.texture&&this._uReflectivityMap&&(r.bindTexture(this._uReflectivityMap,i._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,this._uReflectivityMapMatrix&&a.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,i._reflectivityMap._state.matrix)),i._normalMap&&i._normalMap._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,i._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,i._normalMap._state.matrix)),i._occlusionMap&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,i._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,i._occlusionMap._state.matrix)),i._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&a.uniform1f(this._uDiffuseFresnelEdgeBias,i._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&a.uniform1f(this._uDiffuseFresnelCenterBias,i._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&a.uniform3fv(this._uDiffuseFresnelEdgeColor,i._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&a.uniform3fv(this._uDiffuseFresnelCenterColor,i._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&a.uniform1f(this._uDiffuseFresnelPower,i._diffuseFresnel.power)),i._specularFresnel&&(this._uSpecularFresnelEdgeBias&&a.uniform1f(this._uSpecularFresnelEdgeBias,i._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&a.uniform1f(this._uSpecularFresnelCenterBias,i._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&a.uniform3fv(this._uSpecularFresnelEdgeColor,i._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&a.uniform3fv(this._uSpecularFresnelCenterColor,i._specularFresnel.centerColor),this._uSpecularFresnelPower&&a.uniform1f(this._uSpecularFresnelPower,i._specularFresnel.power)),i._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&a.uniform1f(this._uAlphaFresnelEdgeBias,i._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&a.uniform1f(this._uAlphaFresnelCenterBias,i._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&a.uniform3fv(this._uAlphaFresnelEdgeColor,i._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&a.uniform3fv(this._uAlphaFresnelCenterColor,i._alphaFresnel.centerColor),this._uAlphaFresnelPower&&a.uniform1f(this._uAlphaFresnelPower,i._alphaFresnel.power)),i._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&a.uniform1f(this._uReflectivityFresnelEdgeBias,i._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&a.uniform1f(this._uReflectivityFresnelCenterBias,i._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&a.uniform3fv(this._uReflectivityFresnelEdgeColor,i._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&a.uniform3fv(this._uReflectivityFresnelCenterColor,i._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&a.uniform1f(this._uReflectivityFresnelPower,i._reflectivityFresnel.power)),i._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&a.uniform1f(this._uEmissiveFresnelEdgeBias,i._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&a.uniform1f(this._uEmissiveFresnelCenterBias,i._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&a.uniform3fv(this._uEmissiveFresnelEdgeColor,i._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&a.uniform3fv(this._uEmissiveFresnelCenterColor,i._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&a.uniform1f(this._uEmissiveFresnelPower,i._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&a.uniform3fv(this._uBaseColor,o.baseColor),this._uMaterialMetallic&&a.uniform1f(this._uMaterialMetallic,o.metallic),this._uMaterialRoughness&&a.uniform1f(this._uMaterialRoughness,o.roughness),this._uMaterialSpecularF0&&a.uniform1f(this._uMaterialSpecularF0,o.specularF0),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const t=i._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(r.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uBaseColorMapMatrix&&a.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const n=i._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(r.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicMapMatrix&&a.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const l=i._roughnessMap;l&&l._state.texture&&this._uRoughnessMap&&(r.bindTexture(this._uRoughnessMap,l._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uRoughnessMapMatrix&&a.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,l._state.matrix));const c=i._metallicRoughnessMap;c&&c._state.texture&&this._uMetallicRoughnessMap&&(r.bindTexture(this._uMetallicRoughnessMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&a.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,c._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialGlossiness&&a.uniform1f(this._uMaterialGlossiness,o.glossiness),this._uMaterialReflectivity&&a.uniform1f(this._uMaterialReflectivity,o.reflectivity),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const u=i._diffuseMap;u&&u._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,u._state.matrix));const h=i._specularMap;h&&h._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const p=i._glossinessMap;p&&p._state.texture&&this._uGlossinessMap&&(r.bindTexture(this._uGlossinessMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uGlossinessMapMatrix&&a.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,p._state.matrix));const y=i._specularGlossinessMap;var A,d,f,I;y&&y._state.texture&&this._uSpecularGlossinessMap&&(r.bindTexture(this._uSpecularGlossinessMap,y._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&a.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,y._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix))}this._lastMaterialId=o.id}if(a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),this._uColorize){const e=l.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(a.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}a.uniform3fv(this._uOffset,l.offset),c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(c.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(c.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(c.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(c.flagsBuf),e.bindArray++),c.indicesBuf&&(c.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=c.id),c.indicesBuf?(a.drawElements(c.primitive,c.indicesBuf.numItems,c.indicesBuf.itemType,0),e.drawElements++):c.positions&&(a.drawArrays(a.TRIANGLES,0,c.positions.numItems),e.drawArrays++),p&&a.depthFunc(a.LESS)},Ln.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=e._material,i=t._lightsState,a=t._sectionPlanesState,r=e._material._state;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const l=this._program;this._uPositionsDecodeMatrix=l.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=l.getLocation("uvDecodeMatrix"),this._uModelMatrix=l.getLocation("modelMatrix"),this._uModelNormalMatrix=l.getLocation("modelNormalMatrix"),this._uViewMatrix=l.getLocation("viewMatrix"),this._uViewNormalMatrix=l.getLocation("viewNormalMatrix"),this._uProjMatrix=l.getLocation("projMatrix"),this._uGammaFactor=l.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=l.getLocation("logDepthBufFC"));const o=i.lights;let c;for(var u=0,h=o.length;u<h;u++){switch(c=o[u],c.type){case"ambient":this._uLightAmbient[u]=l.getLocation("lightAmbient");break;case"dir":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=null,this._uLightDir[u]=l.getLocation("lightDir"+u);break;case"point":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=null,this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u);break;case"spot":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=l.getLocation("lightDir"+u),this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u)}c.castsShadow&&(this._uShadowViewMatrix[u]=l.getLocation("shadowViewMatrix"+u),this._uShadowProjMatrix[u]=l.getLocation("shadowProjMatrix"+u))}i.lightMaps.length>0&&(this._uLightMap="lightMap"),i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(u=0,h=a.sectionPlanes.length;u<h;u++)this._uSectionPlanes.push({active:l.getLocation("sectionPlaneActive"+u),pos:l.getLocation("sectionPlanePos"+u),dir:l.getLocation("sectionPlaneDir"+u)});switch(this._uPointSize=l.getLocation("pointSize"),r.type){case"LambertMaterial":this._uMaterialColor=l.getLocation("materialColor"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=l.getLocation("materialAmbient"),this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=l.getLocation("materialShininess"),n._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=l.getLocation("ambientMapMatrix")),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=l.getLocation("reflectivityMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=l.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=l.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=l.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=l.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=l.getLocation("diffuseFresnelPower")),n._specularFresnel&&(this._uSpecularFresnelEdgeBias=l.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=l.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=l.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=l.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=l.getLocation("specularFresnelPower")),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias=l.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=l.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=l.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=l.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=l.getLocation("alphaFresnelPower")),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=l.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=l.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=l.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=l.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=l.getLocation("reflectivityFresnelPower")),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=l.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=l.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=l.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=l.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=l.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=l.getLocation("materialBaseColor"),this._uMaterialMetallic=l.getLocation("materialMetallic"),this._uMaterialRoughness=l.getLocation("materialRoughness"),this._uMaterialSpecularF0=l.getLocation("materialSpecularF0"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=l.getLocation("baseColorMapMatrix")),n._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=l.getLocation("metallicMapMatrix")),n._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=l.getLocation("roughnessMapMatrix")),n._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=l.getLocation("metallicRoughnessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialGlossiness=l.getLocation("materialGlossiness"),this._uMaterialReflectivity=l.getLocation("reflectivityFresnel"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=l.getLocation("glossinessMapMatrix")),n._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=l.getLocation("materialSpecularGlossinessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"))}this._aPosition=l.getAttribute("position"),this._aNormal=l.getAttribute("normal"),this._aUV=l.getAttribute("uv"),this._aColor=l.getAttribute("color"),this._aFlags=l.getAttribute("flags"),this._uClippable=l.getLocation("clippable"),this._uColorize=l.getLocation("colorize"),this._uOffset=l.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},Ln.prototype._bindProgram=function(e){const t=pe.MAX_TEXTURE_UNITS,s=this._scene,n=s.canvas.gl,i=s._lightsState,a=s.camera.project;let r;const l=this._program;if(l.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}for(var o=0,c=i.lights.length;o<c;o++)if(r=i.lights[o],this._uLightAmbient[o])n.uniform4f(this._uLightAmbient[o],r.color[0],r.color[1],r.color[2],r.intensity);else if(this._uLightColor[o]&&n.uniform4f(this._uLightColor[o],r.color[0],r.color[1],r.color[2],r.intensity),this._uLightPos[o]&&(n.uniform3fv(this._uLightPos[o],r.pos),this._uLightAttenuation[o]&&n.uniform1f(this._uLightAttenuation[o],r.attenuation)),this._uLightDir[o]&&n.uniform3fv(this._uLightDir[o],r.dir),r.castsShadow){this._uShadowViewMatrix[o]&&n.uniformMatrix4fv(this._uShadowViewMatrix[o],!1,r.getShadowViewMatrix()),this._uShadowProjMatrix[o]&&n.uniformMatrix4fv(this._uShadowProjMatrix[o],!1,r.getShadowProjMatrix());const s=r.getShadowRenderBuf();s&&(l.bindTexture("shadowMap"+o,s.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}i.lightMaps.length>0&&i.lightMaps[0].texture&&this._uLightMap&&(l.bindTexture(this._uLightMap,i.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),i.reflectionMaps.length>0&&i.reflectionMaps[0].texture&&this._uReflectionMap&&(l.bindTexture(this._uReflectionMap,i.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class Fn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,n=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),i=t._sectionPlanesState.sectionPlanes.length>0,a=!!e._geometry._state.compressGeometry,r=e._state.billboard,l=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// EmphasisFillShaderSource vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 colorize;"),o.push("uniform vec3 offset;"),a&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");if(o.push("uniform vec4 lightAmbient;"),o.push("uniform vec4 fillColor;"),n){o.push("in vec3 normal;"),o.push("uniform mat4 modelNormalMatrix;"),o.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&o.push("uniform vec3 lightPos"+e+";"))}a&&(o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"))}o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),a&&o.push("localPosition = positionsDecodeMatrix * localPosition;");n&&(a?o.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):o.push("vec4 localNormal = vec4(normal, 0.0); "),o.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),o.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),l&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),n&&(o.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),o.push("billboard(modelNormalMatrix2);"),o.push("billboard(viewNormalMatrix2);"),o.push("billboard(modelViewNormalMatrix);")),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n&&o.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),n)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?o.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}o.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),i&&o.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&o.push("gl_PointSize = pointSize;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}"));t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const Hn=new e({}),Un=p.vec3(),Gn=function(e,t){this.id=Hn.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Fn(t),this._allocate(t)},Vn={};Gn.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Vn[t];return s||(s=new Gn(t,e),Vn[t]=s,d.memory.programs++),s._useCount++,s},Gn.prototype.put=function(){0==--this._useCount&&(Hn.removeItem(this.id),this._program&&this._program.destroy(),delete Vn[this._hash],d.memory.programs--)},Gn.prototype.webglContextRestored=function(){this._program=null},Gn.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl,r=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,l=t._state,o=t._geometry._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):i.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,c?L(n.dist,n.dir,c,Un):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(r.id!==this._lastMaterialId){const t=r.fillColor,s=r.backfaces;e.backfaces!==s&&(s?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=s),a.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(o.normalsBuf),e.bindArray++),o.indicesBuf?(o.indicesBuf.bind(),e.bindArray++):o.positionsBuf,this._lastGeometryId=o.id),o.indicesBuf?(a.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positionsBuf&&(a.drawArrays(a.TRIANGLES,0,o.positionsBuf.numItems),e.drawArrays++)},Gn.prototype._allocate=function(e){const t=e.scene,s=t._lightsState,n=t._sectionPlanesState,i=t.canvas.gl;if(this._program=new be(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=s.lights.length;e<t;e++){switch(s.lights[e].type){case"ambient":this._uLightAmbient[e]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=a.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=a.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=a.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+e),pos:a.getLocation("sectionPlanePos"+e),dir:a.getLocation("sectionPlaneDir"+e)});this._uFillColor=a.getLocation("fillColor"),this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._uClippable=a.getLocation("clippable"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uOffset=a.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Gn.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t._lightsState,i=t.camera,a=i.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];this._uLightAmbient[e]?s.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(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))}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor)};class jn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Edges drawing vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec4 edgeColor;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));s&&r.push("out vec4 vWorldPosition;");r.push("out vec4 vColor;"),("spherical"===i||"cylindrical"===i)&&(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.push("vColor = edgeColor;"),s&&r.push("vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const kn=new e({}),Qn=p.vec3(),Wn=function(e,t){this.id=kn.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new jn(t),this._allocate(t)},zn={};Wn.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=zn[t];return s||(s=new Wn(t,e),zn[t]=s,d.memory.programs++),s._useCount++,s},Wn.prototype.put=function(){0==--this._useCount&&(kn.removeItem(this.id),this._program&&this._program.destroy(),delete zn[this._hash],d.memory.programs--)},Wn.prototype.webglContextRestored=function(){this._program=null},Wn.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl;let r;const l=t._state,o=t._geometry,c=o._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(l.originHash,u):i.viewMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,u?L(n.dist,n.dir,u,Qn):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}switch(s){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;a.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let h;a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?h=o._getEdgeIndices():c.primitive===a.LINES&&(h=c.indicesBuf),h&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,h.numItems,h.itemType,0),e.drawElements++)},Wn.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=i.getLocation("edgeColor"),this._aPosition=i.getAttribute("position"),this._uClippable=i.getLocation("clippable"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uOffset=i.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Wn.prototype._bindProgram=function(e){const t=this._program,s=this._scene,n=s.canvas.gl,i=s.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor)};class Kn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh picking vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("out vec4 vViewPosition;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==i&&"cylindrical"!==i||(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"));r.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(i.push("uniform vec4 pickColor;"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = pickColor; "),i.push("}"),i}(e)}}const Yn=p.vec3(),Xn=function(e,t){this._hash=e,this._shaderSource=new Kn(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},qn={};Xn.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=qn[t];if(!s){if(s=new Xn(t,e),s.errors)return console.log(s.errors.join("\n")),null;qn[t]=s,d.memory.programs++}return s._useCount++,s},Xn.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete qn[this._hash],d.memory.programs--)},Xn.prototype.webglContextRestored=function(){this._program=null},Xn.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(i.originHash,l):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?L(s.dist,s.dir,l,Yn):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}if(a.id!==this._lastMaterialId){const t=a.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=a.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=a.id}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id);var o=t._state.pickID;const c=o>>24&255,u=o>>16&255,h=o>>8&255,p=255&o;n.uniform4f(this._uPickColor,p/255,h/255,u/255,c/255),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Xn.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uPickColor=n.getLocation("pickColor"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},Xn.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Jn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry;e._state.billboard,e._state.stationary;const i=[];i.push("#version 300 es"),i.push("// Surface picking vertex shader"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform vec3 offset;"),s&&(i.push("uniform bool clippable;"),i.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"));i.push("out vec4 vColor;"),n&&i.push("uniform mat4 positionsDecodeMatrix;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),n&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push(" vec4 worldPosition = modelMatrix * localPosition; "),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&i.push(" vWorldPosition = worldPosition;");i.push(" vColor = color;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return i.push("gl_Position = clipPos;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Surface picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = vColor;"),i.push("}"),i}(e)}}const Zn=p.vec3(),$n=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Jn(t),this._allocate(t)},ei={};$n.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=ei[t];if(!s){if(s=new $n(t,e),s.errors)return console.log(s.errors.join("\n")),null;ei[t]=s,d.memory.programs++}return s._useCount++,s},$n.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ei[this._hash],d.memory.programs--)},$n.prototype.webglContextRestored=function(){this._program=null},$n.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry,l=t._geometry._state,o=t.origin,c=a.backfaces,u=a.frontface,h=s.camera.project,p=r._getPickTrianglePositions(),A=r._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}if(n.uniformMatrix4fv(this._uViewMatrix,!1,o?e.getRTCPickViewMatrix(i.originHash,o):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,o?L(s.dist,s.dir,o,Zn):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.logarithmicDepthBufferEnabled&&n.uniform1f(this._uZFar,s.camera.project.far),e.backfaces!==c&&(c?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=c),e.frontface!==u&&(u?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=u),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(p,l.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT)):this._aPosition.bindArrayBuffer(p),A.bind(),n.enableVertexAttribArray(this._aColor.location),n.vertexAttribPointer(this._aColor.location,A.itemSize,A.itemType,!0,0,0),n.drawArrays(l.primitive,0,p.numItems/3)},$n.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._aColor=n.getAttribute("color"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))};class ti{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push("}"),i}(e)}}const si=p.vec3(),ni=function(e,t){this._hash=e,this._shaderSource=new ti(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ii={};ni.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=ii[t];if(!s){if(s=new ni(t,e),s.errors)return console.log(s.errors.join("\n")),null;ii[t]=s,d.memory.programs++}return s._useCount++,s},ni.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ii[this._hash],d.memory.programs--)},ni.prototype.webglContextRestored=function(){this._program=null},ni.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._material._state,a=t._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=i.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=i.id}const o=s.camera;if(n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCViewMatrix(a.originHash,l):o.viewMatrix),a.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?L(s.dist,s.dir,l,si):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),n.uniformMatrix4fv(this._uModelMatrix,n.FALSE,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},ni.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ni.prototype._bindProgram=function(e){const t=this._scene,s=t.camera.project,n=t.canvas.gl;if(this._program.bind(),e.useProgram++,n.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class ai{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,n=[];n.push("// Mesh shadow vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t&&n.push("out vec4 vWorldPosition;");n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("worldPosition = modelMatrix * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&n.push("vWorldPosition = worldPosition;");return n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("// Mesh shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("vec4 encodeFloat( const in float depth ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(depth * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return i.push("outColor = encodeFloat(gl_FragCoord.z);"),i.push("}"),i}(e)}}const ri=function(e,t){this._hash=e,this._shaderSource=new ai(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},li={};ri.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let n=li[s];if(!n){if(n=new ri(s,e),n.errors)return console.log(n.errors.join("\n")),null;li[s]=n,d.memory.programs++}return n._useCount++,n},ri.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete li[this._hash],d.memory.programs--)},ri.prototype.webglContextRestored=function(){this._program=null},ri.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,n=t._material._state,i=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){const t=n.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=n.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),e.lineWidth!==n.lineWidth&&(s.lineWidth(n.lineWidth),e.lineWidth=n.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,n.pointSize),this._lastMaterialId=n.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),i.combineGeometry){const n=t.vertexBufs;n.id!==this._lastVertexBufsId&&(n.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=n.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),i.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,i.positionsDecodeMatrix),i.combineGeometry?i.indicesBufCombined&&(i.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),i.indicesBuf&&(i.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=i.id),i.combineGeometry?i.indicesBufCombined&&(s.drawElements(i.primitive,i.indicesBufCombined.numItems,i.indicesBufCombined.itemType,0),e.drawElements++):i.indicesBuf?(s.drawElements(i.primitive,i.indicesBuf.numItems,i.indicesBuf.itemType,0),e.drawElements++):i.positions&&(s.drawArrays(s.TRIANGLES,0,i.positions.numItems),e.drawArrays++)},ri.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ri.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.sectionPlanes.length>0){let e,t,i,a,r;for(let l=0,o=this._uSectionPlanes.length;l<o;l++)e=this._uSectionPlanes[l],t=e.active,i=n.sectionPlanes[l],t&&s.uniform1i(t,i.active),a=e.pos,a&&s.uniform3fv(e.pos,i.pos),r=e.dir,r&&s.uniform3fv(e.dir,i.dir)}};class oi{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const ci=p.OBB3(),ui=p.vec4(),hi=p.vec4(),pi=p.vec4(),Ai=p.vec3([1,0,0]),di=p.vec3([0,1,0]),fi=p.vec3([0,0,1]),Ii=p.vec3(3),yi=p.vec3(3),mi=p.identityMat4();class vi extends _{constructor(e,t={}){super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new oi,this._state=new We({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:p.vec3(),origin:null,originHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=p.vec3(),this._quaternion=p.identityQuaternion(),this._rotation=p.vec3(),this._position=p.vec3(),this._worldMatrix=p.identityMat4(),this._worldNormalMatrix=p.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const s=t.origin||t.rtcCenter;if(s&&(this._state.origin=p.vec3(s),this._state.originHash=s.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),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.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),p.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=p.identityMat4()),p.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=p.identityMat4()),this.__localMatrix.set(e||mi),p.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=p.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const s=!!e;this.scene._objectColorizeUpdated(this,s),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const s=null!=e;t[3]=s?e:1,this.scene._objectOpacityUpdated(this,s),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Ln.get(this),this._emphasisFillRenderer=Gn.get(this),this._emphasisEdgesRenderer=Wn.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Xn.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=ni.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)p.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=p.mat4()),p.transposeMat4(this._worldMatrix,this._worldNormalMatrix),p.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=p.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),s.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){p.transformOBB3(e,this._geometry.obb,ci),p.OBB3ToAABB3(ci,t);const s=this._state.offset;if(t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[0],t[4]+=s[1],t[5]+=s[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return ui[0]=e[0],ui[1]=e[1],ui[2]=e[2],ui[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(ui,hi),p.mulQuaternions(this.quaternion,hi,pi),this.quaternion=pi,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return ui[0]=e[0],ui[1]=e[1],ui[2]=e[2],ui[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(ui,hi),p.mulQuaternions(hi,this.quaternion,hi),this}rotateX(e){return this.rotate(Ai,e)}rotateY(e){return this.rotate(di,e)}rotateZ(e){return this.rotate(fi,e)}translate(e,t){return p.vec3ApplyQuaternion(this.quaternion,e,Ii),p.mulVec3Scalar(Ii,t,yi),p.addVec3(this.position,yi,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ai,e)}translateY(e){return this.translate(di,e)}translateZ(e){return this.translate(fi,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s],n=this.renderFlags;if(t.active)if(this._state.origin){const e=p.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const i=0===e;n.sectionPlanesActivePerLayer[s]=i}else n.sectionPlanesActivePerLayer[s]=!0;else n.sectionPlanesActivePerLayer[s]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=Ln.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=Ln.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Gn.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Gn.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Gn.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=ni.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=ri.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=Xn.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=$n.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,s){wi(this,e,t,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const wi=function(){const e=p.vec3(),t=p.vec3(),s=p.vec3(),n=p.vec3(),i=p.vec3(),a=p.vec3(),r=p.vec4(),l=p.vec3(),o=p.vec3(),c=p.vec3(),u=p.vec3(),h=p.vec3(),A=p.vec3(),d=p.vec3(),f=p.vec3(),I=p.vec3(),y=p.vec4(),m=p.vec4(),v=p.vec4(),w=p.vec3(),g=p.vec3(),T=p.vec3(),E=p.vec3(),b=p.vec3(),D=p.vec3(),P=p.vec3(),R=p.vec3(),C=p.vec3(),_=p.vec3(),B=p.vec3();return function(S,N,x,L){var M=L.primIndex;if(null!=M&&M>-1){const G=S.geometry._state,V=S.scene,j=V.camera,k=V.canvas;if("triangles"===G.primitiveName){L.primitive="triangle";const V=M,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var F=Q[V+0],H=Q[V+1],U=Q[V+2];a[0]=F,a[1]=H,a[2]=U,L.indices=a,z=3*F,K=3*H,Y=3*U}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],n[0]=W[K+0],n[1]=W[K+1],n[2]=W[K+2],i[0]=W[Y+0],i[1]=W[Y+1],i[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(bt.decompressPosition(s,e,s),bt.decompressPosition(n,e,n),bt.decompressPosition(i,e,i))}L.canvasPos?p.canvasPosToLocalRay(k.canvas,S.origin?O(N,S.origin):N,x,S.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&p.worldRayToLocalRay(S.worldMatrix,L.origin,L.direction,e,t),p.normalizeVec3(t),p.rayPlaneIntersect(e,t,s,n,i,r),L.localPos=r,L.position=r,y[0]=r[0],y[1]=r[1],y[2]=r[2],y[3]=1,p.transformVec4(S.worldMatrix,y,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],L.canvasPos&&S.origin&&(l[0]+=S.origin[0],l[1]+=S.origin[1],l[2]+=S.origin[2]),L.worldPos=l,p.transformVec4(j.matrix,m,v),o[0]=v[0],o[1]=v[1],o[2]=v[2],L.viewPos=o,p.cartesianToBarycentric(r,s,n,i,c),L.bary=c;const X=G.normals;if(X){if(G.compressGeometry){const e=3*F,t=3*H,s=3*U;bt.decompressNormal(X.subarray(e,e+2),u),bt.decompressNormal(X.subarray(t,t+2),h),bt.decompressNormal(X.subarray(s,s+2),A)}else u[0]=X[z],u[1]=X[z+1],u[2]=X[z+2],h[0]=X[K],h[1]=X[K+1],h[2]=X[K+2],A[0]=X[Y],A[1]=X[Y+1],A[2]=X[Y+2];const e=p.addVec3(p.addVec3(p.mulVec3Scalar(u,c[0],w),p.mulVec3Scalar(h,c[1],g),T),p.mulVec3Scalar(A,c[2],E),b);L.worldNormal=p.normalizeVec3(p.transformVec3(S.worldNormalMatrix,e,D))}const q=G.uv;if(q){if(d[0]=q[2*F],d[1]=q[2*F+1],f[0]=q[2*H],f[1]=q[2*H+1],I[0]=q[2*U],I[1]=q[2*U+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(bt.decompressUV(d,e,d),bt.decompressUV(f,e,f),bt.decompressUV(I,e,I))}L.uv=p.addVec3(p.addVec3(p.mulVec2Scalar(d,c[0],P),p.mulVec2Scalar(f,c[1],R),C),p.mulVec2Scalar(I,c[2],_),B)}}}}}();function gi(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let n=e.height||1;n<0&&(console.error("negative height not allowed - will invert"),n*=-1);let i=e.radialSegments||32;i<0&&(console.error("negative radialSegments not allowed - will invert"),i*=-1),i<3&&(i=3);let a=e.heightSegments||1;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a<1&&(a=1);const r=!!e.openEnded;let l=e.center;const o=l?l[0]:0,c=l?l[1]:0,u=l?l[2]:0,h=n/2,p=n/a,A=2*Math.PI/i,d=1/i,f=(t-s)/a,I=[],y=[],v=[],w=[];let g,T,E,b,D,P,R,C,_,B,O;const S=(90-180*Math.atan(n/(s-t))/Math.PI)/90;for(g=0;g<=a;g++)for(D=t-g*f,P=h-g*p,T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),y.push(D*E),y.push(S),y.push(D*b),v.push(T*d),v.push(1*g/a),I.push(D*E+o),I.push(P+c),I.push(D*b+u);for(g=0;g<a;g++)for(T=0;T<=i;T++)R=g*(i+1)+T,C=R+i,w.push(R),w.push(C),w.push(C+1),w.push(R),w.push(C+1),w.push(R+1);if(!r&&t>0){for(_=I.length/3,y.push(0),y.push(1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,y.push(t*E),y.push(1),y.push(t*b),v.push(B),v.push(O),I.push(t*E+o),I.push(h+c),I.push(t*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(R),w.push(R+1),w.push(l)}if(!r&&s>0){for(_=I.length/3,y.push(0),y.push(-1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(0-h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,y.push(s*E),y.push(-1),y.push(s*b),v.push(B),v.push(O),I.push(s*E+o),I.push(0-h+c),I.push(s*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(l),w.push(R+1),w.push(R)}return m.apply(e,{positions:I,normals:y,uv:v,indices:w})}function Ti(e={}){const t=e.lod||1,s=e.center?e.center[0]:0,n=e.center?e.center[1]:0,i=e.center?e.center[2]:0;let a=e.radius||1;a<0&&(console.error("negative radius not allowed - will invert"),a*=-1);let r=e.heightSegments||18;r<0&&(console.error("negative heightSegments not allowed - will invert"),r*=-1),r=Math.floor(t*r),r<18&&(r=18);let l=e.widthSegments||18;l<0&&(console.error("negative widthSegments not allowed - will invert"),l*=-1),l=Math.floor(t*l),l<18&&(l=18);const o=[],c=[],u=[],h=[];let p,A,d,f,I,y,v,w,g,T,E,b,D,P,R;for(p=0;p<=r;p++)for(d=p*Math.PI/r,f=Math.sin(d),I=Math.cos(d),A=0;A<=l;A++)y=2*A*Math.PI/l,v=Math.sin(y),w=Math.cos(y),g=w*f,T=I,E=v*f,b=1-A/l,D=p/r,c.push(g),c.push(T),c.push(E),u.push(b),u.push(D),o.push(s+a*g),o.push(n+a*T),o.push(i+a*E);for(p=0;p<r;p++)for(A=0;A<l;A++)P=p*(l+1)+A,R=P+l+1,h.push(P+1),h.push(R+1),h.push(R),h.push(P+1),h.push(R),h.push(P);return m.apply(e,{positions:o,normals:c,uv:u,indices:h})}const Ei={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function bi(e={}){var t=e.origin||[0,0,0],s=t[0],n=t[1],i=t[2],a=e.size||1,r=[],l=[],o=e.text;m.isNumeric(o)&&(o=""+o);for(var c,u,h,p,A,d,f,I,y,v=(o||"").split("\n"),w=0,g=0,T=.04,E=0;E<v.length;E++){c=0,h=(u=v[E]).length;for(var b=0;b<h;b++)if(p=Ei[u.charAt(b)]){A=1,d=-1,f=-1,I=p.points.length;for(var D=0;D<I;D++)-1!==(y=p.points[D])[0]||-1!==y[1]?(r.push(c+y[0]*a*T+s),r.push(g+y[1]*a*T+n),r.push(0+i),-1===d?d=w:(-1===f||(d=f),f=w),w++,A?A=!1:(l.push(d),l.push(f))):A=1;c+=p.width*T*a}g-=35*T*a}return m.apply(e,{primitive:"lines",positions:r,indices:l})}class Di extends r{constructor(e,t){super("AxisGizmo",e,t=t||{});const s=e.scene.camera;t.canvasId||t.canvasElement||this.error("Config expected: either 'canvasId' or 'canvasElement'");try{this._axisGizmoScene=new As(e,{canvasId:t.canvasId,canvasElement:t.canvasElement,transparent:!0})}catch(e){return void this.error(e)}const n=this._axisGizmoScene;n.clearLights(),new ft(n,{color:[.45,.45,.5],intensity:.9}),new dt(n,{dir:[-.5,.5,-.6],color:[.8,.8,.7],intensity:1,space:"view"}),new dt(n,{dir:[.5,-.5,-.6],color:[.8,.8,.8],intensity:1,space:"view"});const i=n.camera;s.on("matrix",(function(){const e=s.eye,t=s.look,n=s.up,a=p.mulVec3Scalar(p.normalizeVec3(p.subVec3(e,t,[])),22);i.look=[0,0,0],i.eye=a,i.up=n}));const a=new Rt(n,gi({radiusTop:.01,radiusBottom:.6,height:1.7,radialSegments:20,heightSegments:1,openEnded:!1})),r=new Rt(n,gi({radiusTop:.2,radiusBottom:.2,height:4.5,radialSegments:20,heightSegments:1,openEnded:!1})),l=new St(n,{diffuse:[1,.3,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),o=new St(n,{emissive:[1,.3,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),c=new St(n,{diffuse:[.3,1,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),u=new St(n,{emissive:[.3,1,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),h=new St(n,{diffuse:[.3,.3,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),A=new St(n,{emissive:[.3,.3,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),d=new St(n,{diffuse:[.5,.5,.5],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2});this._meshes=[new vi(n,{geometry:new Rt(n,Ti({radius:9,heightSegments:60,widthSegments:60})),material:new St(n,{diffuse:[0,0,0],emissive:[.1,.1,.1],ambient:[.1,.1,.2],specular:[0,0,0],alpha:.4,alphaMode:"blend",frontface:"cw"}),pickable:!1,collidable:!1,visible:!1!==t.visible}),new vi(n,{geometry:new Rt(n,Ti({radius:1})),material:d,pickable:!1,collidable:!1,visible:!1!==t.visible}),new vi(n,{geometry:a,material:l,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[5,0,0],rotation:[0,0,-90]}),new vi(n,{geometry:r,material:l,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[2,0,0],rotation:[0,0,90]}),new vi(n,{geometry:new Rt(n,bi({text:"X",size:1.5})),material:o,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[7,0,0],billboard:"spherical"}),new vi(n,{geometry:a,material:c,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,5,0]}),new vi(n,{geometry:r,material:c,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,2,0]}),new vi(n,{geometry:new Rt(n,bi({text:"Y",size:1.5})),material:u,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,7,0],billboard:"spherical"}),new vi(n,{geometry:a,material:h,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,0,5],rotation:[90,0,0]}),new vi(n,{geometry:r,material:h,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,0,2],rotation:[90,0,0]}),new vi(n,{geometry:new Rt(n,bi({text:"Z",size:1.5})),material:A,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,0,7],billboard:"spherical"})]}setVisible(e){for(let t=0;t<this._meshes.length;t++)this._meshes[t].visible=e}destroy(){this._axisGizmoCanvas=null,this._axisGizmoScene.destroy(),this._axisGizmoScene=null,super.destroy()}}class Pi extends _{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new We({active:!0,pos:p.vec3(),dir:p.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-p.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-p.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-p.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const Ri=p.vec4(4),Ci=p.vec4(),_i=p.vec4(),Bi=p.vec3([1,0,0]),Oi=p.vec3([0,1,0]),Si=p.vec3([0,0,1]),Ni=p.vec3(3),xi=p.vec3(3),Li=p.identityMat4();class Mi extends _{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=p.vec3(),this._quaternion=p.identityQuaternion(),this._rotation=p.vec3(),this._position=p.vec3(),this._offset=p.vec3(),this._localMatrix=p.identityMat4(),this._worldMatrix=p.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let s=0,n=e.length;s<n;s++)this.addChild(e[s],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=p.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,s=this._children.length;t<s;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,s=this._children.length;e<s;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,s=this._children.length;t<s;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)p.mulMat4(this._parentNode.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._children)for(let t=0,s=e._children.length;t<s;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=p.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;p.collapseAABB3(this._aabb);for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e.collidable&&p.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+m.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,s=this._children.length;t<s;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+m.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),p.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=p.identityMat4()),this._localMatrix.set(e||Li),p.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=p.identityMat4()),p.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 Ri[0]=e[0],Ri[1]=e[1],Ri[2]=e[2],Ri[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(Ri,Ci),p.mulQuaternions(this.quaternion,Ci,_i),this.quaternion=_i,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ri[0]=e[0],Ri[1]=e[1],Ri[2]=e[2],Ri[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(Ri,Ci),p.mulQuaternions(Ci,this.quaternion,Ci),this}rotateX(e){return this.rotate(Bi,e)}rotateY(e){return this.rotate(Oi,e)}rotateZ(e){return this.rotate(Si,e)}translate(e,t){return p.vec3ApplyQuaternion(this.quaternion,e,Ni),p.mulVec3Scalar(Ni,t,xi),p.addVec3(this.position,xi,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Bi,e)}translateY(e){return this.translate(Oi,e)}translateZ(e){return this.translate(Si,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,n=e.length;s<n;s++)t=e[s],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}class Fi extends _t{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new We({type:"LambertMaterial",ambient:p.vec3([1,1,1]),color:p.vec3([1,1,1]),emissive:p.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const Hi={opaque:0,mask:1,blend:2},Ui=["opaque","mask","blend"];class Gi extends _t{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new We({type:"MetallicMaterial",baseColor:p.vec4([1,1,1]),emissive:p.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=Hi[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Ui[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const Vi={opaque:0,mask:1,blend:2},ji=["opaque","mask","blend"];class ki extends _t{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new We({type:"SpecularMaterial",diffuse:p.vec3([1,1,1]),emissive:p.vec3([0,0,0]),specular:p.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=Vi[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return ji[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}function Qi(e,t,s=null){let n;const i=t;if(1009===i)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(1015===i)return e.FLOAT;if(1016===i)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1023===i)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(1028===i)return e.RED;if(1022===i)return e.RGBA;if(1029===i)return e.RED_INTEGER;if(1030===i)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i)if(3001===s){const t=Ve(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===i)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=Ve(e,"WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===i)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){const t=Ve(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===i)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i){const t=Ve(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===i||37496===i){const t=Ve(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===i)return 3001===s?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){const t=Ve(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===i){const t=Ve(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===i)return 3001===s?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===i?e.UNSIGNED_INT_24_8:1e3===i?e.REPEAT:1001===i?e.CLAMP_TO_EDGE:1004===i||1005===i?e.NEAREST_MIPMAP_LINEAR:1007===i?e.LINEAR_MIPMAP_NEAREST:1008===i?e.LINEAR_MIPMAP_LINEAR:1003===i?e.NEAREST:1006===i?e.LINEAR:null}const Wi=new Uint8Array([0,0,0,1]);class zi{constructor({gl:e,target:t,format:s,type:n,wrapS:i,wrapT:a,wrapR:r,encoding:l,preloadColor:o,premultiplyAlpha:c,flipY:u}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!u,this.unpackAlignment=4,this.wrapS=i||1e3,this.wrapT=a||1e3,this.wrapR=r||1e3,this.encoding=l||3001,this.texture=e.createTexture(),o&&this.setPreloadColor(o),this.allocated=!0}setPreloadColor(e){e?(Wi[0]=Math.floor(255*e[0]),Wi[1]=Math.floor(255*e[1]),Wi[2]=Math.floor(255*e[2]),Wi[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Wi[0]=0,Wi[1]=0,Wi[2]=0,Wi[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let s=0,n=e.length;s<n;s++)t.texImage2D(e[s],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const s=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let n=!1;s.bindTexture(this.target,this.texture);const i=s.getParameter(s.UNPACK_FLIP_Y_WEBGL);s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY);const a=s.getParameter(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL);s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const r=s.getParameter(s.UNPACK_ALIGNMENT);s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment);const l=s.getParameter(s.UNPACK_COLORSPACE_CONVERSION_WEBGL);s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Qi(s,this.minFilter);s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,o),o!==s.NEAREST_MIPMAP_NEAREST&&o!==s.LINEAR_MIPMAP_NEAREST&&o!==s.NEAREST_MIPMAP_LINEAR&&o!==s.LINEAR_MIPMAP_LINEAR||(n=!0);const c=Qi(s,this.magFilter);c&&s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,c);const u=Qi(s,this.wrapS);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,u);const h=Qi(s,this.wrapT);h&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,h);const p=Qi(s,this.format,this.encoding),A=Qi(s,this.type),d=Ki(s,this.internalFormat,p,A,this.encoding,!1);if(this.target===s.TEXTURE_CUBE_MAP){if(m.isArray(e)){const t=e,n=[s.TEXTURE_CUBE_MAP_POSITIVE_X,s.TEXTURE_CUBE_MAP_NEGATIVE_X,s.TEXTURE_CUBE_MAP_POSITIVE_Y,s.TEXTURE_CUBE_MAP_NEGATIVE_Y,s.TEXTURE_CUBE_MAP_POSITIVE_Z,s.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,i=n.length;e<i;e++)s.texImage2D(n[e],0,d,p,A,t[e])}}else s.texImage2D(s.TEXTURE_2D,0,d,p,A,e);n&&s.generateMipmap(this.target),s.bindTexture(this.target,null),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a),s.pixelStorei(s.UNPACK_ALIGNMENT,r),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l)}setCompressedData({mipmaps:e,props:t={}}){const s=this.gl,n=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),s.activeTexture(s.TEXTURE0+0),s.bindTexture(this.target,this.texture);let i=e.length>1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const a=Qi(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);const r=Qi(s,this.wrapT);if(r&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,r),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Qi(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}i?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Yi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Yi(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Qi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Qi(s,this.magFilter)));const l=Qi(s,this.format,this.encoding),o=Qi(s,this.type),c=Ki(s,this.internalFormat,l,o,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,c,e[0].width,e[0].height);for(let t=0,n=e.length;t<n;t++){const n=e[t];1023!==this.format?null!==l?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,n.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):s.texSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,o,n.data)}s.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const s=Qi(t,e.minFilter);s&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,s),s!==t.NEAREST_MIPMAP_NEAREST&&s!==t.LINEAR_MIPMAP_NEAREST&&s!==t.NEAREST_MIPMAP_LINEAR&&s!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const s=Qi(t,e.magFilter);s&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,s))}if(void 0!==e.wrapS){const s=Qi(t,e.wrapS);s&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,s))}if(void 0!==e.wrapT){const s=Qi(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function Ki(e,t,s,n,i,a=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let r=s;return s===e.RED&&(n===e.FLOAT&&(r=e.R32F),n===e.HALF_FLOAT&&(r=e.R16F),n===e.UNSIGNED_BYTE&&(r=e.R8)),s===e.RG&&(n===e.FLOAT&&(r=e.RG32F),n===e.HALF_FLOAT&&(r=e.RG16F),n===e.UNSIGNED_BYTE&&(r=e.RG8)),s===e.RGBA&&(n===e.FLOAT&&(r=e.RGBA32F),n===e.HALF_FLOAT&&(r=e.RGBA16F),n===e.UNSIGNED_BYTE&&(r=3001===i&&!1===a?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT_4_4_4_4&&(r=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(r=e.RGB5_A1)),r!==e.R16F&&r!==e.R32F&&r!==e.RG16F&&r!==e.RG32F&&r!==e.RGBA16F&&r!==e.RGBA32F||Ve(e,"EXT_color_buffer_float"),r}function Yi(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Xi(e){if(!qi(e.width)||!qi(e.height)){const t=document.createElement("canvas");t.width=Ji(e.width),t.height=Ji(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function qi(e){return 0==(e&e-1)}function Ji(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Zi extends _{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new We({texture:new zi({gl:this.scene.canvas.gl}),matrix:p.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=p.vec2([0,0]),this._scale=p.vec2([1,1]),this._rotate=p.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new zi({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=p.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=p.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?p.mulMat4(t,s):s),0!==this._rotate&&(s=p.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?p.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Xi(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=Xi(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}class $i extends _{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new We({edgeColor:p.vec3([0,0,0]),centerColor:p.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const ea=d.memory,ta=p.AABB3();class sa extends It{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new We({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=p.OBB3();const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var i;if(t.positionsDecodeMatrix);else{const e=bt.getPositionsBounds(t.positions),a=bt.compressPositions(t.positions,e.min,e.max);i=a.quantized,s.positionsDecodeMatrix=a.decodeMatrix,s.positionsBuf=new De(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),ea.positions+=s.positionsBuf.numItems,p.positions3ToAABB3(t.positions,this._aabb),p.positions3ToAABB3(i,ta,s.positionsDecodeMatrix),p.AABB3ToOBB3(ta,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new De(n,n.ARRAY_BUFFER,e,e.length,4,n.STATIC_DRAW),ea.colors+=s.colorsBuf.numItems}if(t.uv){const e=bt.getUVBounds(t.uv),i=bt.compressUVs(t.uv,e.min,e.max),a=i.quantized;s.uvDecodeMatrix=i.decodeMatrix,s.uvBuf=new De(n,n.ARRAY_BUFFER,a,a.length,2,n.STATIC_DRAW),ea.uvs+=s.uvBuf.numItems}if(t.normals){const e=bt.compressNormals(t.normals);let i=s.compressGeometry;s.normalsBuf=new De(n,n.ARRAY_BUFFER,e,e.length,3,n.STATIC_DRAW,i),ea.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,e,e.length,1,n.STATIC_DRAW),ea.indices+=s.indicesBuf.numItems;const a=yt(i,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),ea.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),ea.meshes--}}var na={};function ia(e,t={}){return new Promise((function(s,n){t.src||(console.error("load3DSGeometry: Parameter expected: src"),n());var i=e.canvas.spinner;i.processes++,m.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),i.processes--,n());var a=na.parse.from3DS(e).edit.objects[0].mesh,r=a.vertices,l=a.uvt,o=a.indices;i.processes--,s(m.apply(t,{primitive:"triangles",positions:r,normals:null,uv:l,indices:o}))}),(function(e){console.error("load3DSGeometry: "+e),i.processes--,n()}))}))}function aa(e,t={}){return new Promise((function(s,n){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),n());var i=e.canvas.spinner;i.processes++,m.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),i.processes--,n());for(var a=na.parse.fromOBJ(e),r=na.edit.unwrap(a.i_verts,a.c_verts,3),l=na.edit.unwrap(a.i_norms,a.c_norms,3),o=na.edit.unwrap(a.i_uvt,a.c_uvt,2),c=new Int32Array(a.i_verts.length),u=0;u<a.i_verts.length;u++)c[u]=u;i.processes--,s(m.apply(t,{primitive:"triangles",positions:r,normals:l.length>0?l:null,autoNormals:0===l.length,uv:o,indices:c}))}),(function(e){console.error("loadOBJGeometry: "+e),i.processes--,n()}))}))}function ra(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let n=e.zSize||1;n<0&&(console.error("negative zSize not allowed - will invert"),n*=-1);const i=e.center,a=i?i[0]:0,r=i?i[1]:0,l=i?i[2]:0,o=-t+a,c=-s+r,u=-n+l,h=t+a,p=s+r,A=n+l;return m.apply(e,{primitive:"lines",positions:[o,c,u,o,c,A,o,p,u,o,p,A,h,c,u,h,c,A,h,p,u,h,p,A],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function la(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let s=e.divisions||1;s<0&&(console.error("negative divisions not allowed - will invert"),s*=-1),s<1&&(s=1),t=t||10,s=s||10;const n=t/s,i=t/2,a=[],r=[];let l=0;for(let e=0,t=-i;e<=s;e++,t+=n)a.push(-i),a.push(0),a.push(t),a.push(i),a.push(0),a.push(t),a.push(t),a.push(0),a.push(-i),a.push(t),a.push(0),a.push(i),r.push(l++),r.push(l++),r.push(l++),r.push(l++);return m.apply(e,{primitive:"lines",positions:a,indices:r})}function oa(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let n=e.xSegments||1;n<0&&(console.error("negative xSegments not allowed - will invert"),n*=-1),n<1&&(n=1);let i=e.xSegments||1;i<0&&(console.error("negative zSegments not allowed - will invert"),i*=-1),i<1&&(i=1);const a=e.center,r=a?a[0]:0,l=a?a[1]:0,o=a?a[2]:0,c=t/2,u=s/2,h=Math.floor(n)||1,p=Math.floor(i)||1,A=h+1,d=p+1,f=t/h,I=s/p,y=new Float32Array(A*d*3),v=new Float32Array(A*d*3),w=new Float32Array(A*d*2);let g,T,E,b,D,P,R,C=0,_=0;for(g=0;g<d;g++){const e=g*I-u;for(T=0;T<A;T++)E=T*f-c,y[C]=E+r,y[C+1]=l,y[C+2]=-e+o,v[C+2]=-1,w[_]=T/h,w[_+1]=(p-g)/p,C+=3,_+=2}C=0;const B=new(y.length/3>65535?Uint32Array:Uint16Array)(h*p*6);for(g=0;g<p;g++)for(T=0;T<h;T++)b=T+A*g,D=T+A*(g+1),P=T+1+A*(g+1),R=T+1+A*g,B[C]=R,B[C+1]=D,B[C+2]=b,B[C+3]=R,B[C+4]=P,B[C+5]=D,C+=6;return m.apply(e,{positions:y,normals:v,uv:w,indices:B})}function ca(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let s=e.tube||.3;s<0&&(console.error("negative tube not allowed - will invert"),s*=-1);let n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<4&&(n=4);let i=e.tubeSegments||24;i<0&&(console.error("negative tubeSegments not allowed - will invert"),i*=-1),i<4&&(i=4);let a=e.arc||2*Math.PI;a<0&&(console.warn("negative arc not allowed - will invert"),a*=-1),a>360&&(a=360);const r=e.center;let l=r?r[0]:0,o=r?r[1]:0;const c=r?r[2]:0,u=[],h=[],A=[],d=[];let f,I,y,v,w,g,T,E,b,D,P,R;for(E=0;E<=i;E++)for(T=0;T<=n;T++)f=T/n*a,I=.785398+E/i*Math.PI*2,l=t*Math.cos(f),o=t*Math.sin(f),y=(t+s*Math.cos(I))*Math.cos(f),v=(t+s*Math.cos(I))*Math.sin(f),w=s*Math.sin(I),u.push(y+l),u.push(v+o),u.push(w+c),A.push(1-T/n),A.push(E/i),g=p.normalizeVec3(p.subVec3([y,v,w],[l,o,c],[]),[]),h.push(g[0]),h.push(g[1]),h.push(g[2]);for(E=1;E<=i;E++)for(T=1;T<=n;T++)b=(n+1)*E+T-1,D=(n+1)*(E-1)+T-1,P=(n+1)*(E-1)+T,R=(n+1)*E+T,d.push(b),d.push(D),d.push(P),d.push(P),d.push(R),d.push(b);return m.apply(e,{positions:u,normals:h,uv:A,indices:d})}na.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},na.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(na.parse._buffToStr(e));window.location.href=s},na.clone=function(e){return JSON.parse(JSON.stringify(e))},na.bin={},na.bin.f=new Float32Array(1),na.bin.fb=new Uint8Array(na.bin.f.buffer),na.bin.rf=function(e,t){for(var s=na.bin.f,n=na.bin.fb,i=0;i<4;i++)n[i]=e[t+i];return s[0]},na.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},na.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},na.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},na.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},na.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},na.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},na.parse={},na.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",n=0;n<t.length;n++)s=s.concat(String.fromCharCode(t[n]));return s},na.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),s=new Uint8Array(t),n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t},na.parse._readLine=function(e,t){for(var s="";10!=e[t];)s+=String.fromCharCode(e[t++]);return s},na.parse.fromJSON=function(e){return JSON.parse(na.parse._buffToStr(e))},na.parse.toJSON=function(e){var t=JSON.stringify(e);return na.parse._strToBuff(t)},na.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},s={from:0,to:0},n=0,i=new Uint8Array(e);n<i.length;){var a=na.parse._readLine(i,n);n+=a.length+1;var r=(a=(a=a.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==r[0]&&(s.to=t.i_verts.length,null==t.groups[r[1]]&&(t.groups[r[1]]={from:t.i_verts.length,to:0}),s=t.groups[r[1]]),"v"==r[0]){var l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_verts.push(l,o,c)}if("vt"==r[0]){l=parseFloat(r[1]),o=1-parseFloat(r[2]);t.c_uvt.push(l,o)}if("vn"==r[0]){l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_norms.push(l,o,c)}if("f"==r[0]){var u=r[1].split("/"),h=r[2].split("/"),p=r[3].split("/"),A=parseInt(u[0])-1,d=parseInt(h[0])-1,f=parseInt(p[0])-1,I=parseInt(u[1])-1,y=parseInt(h[1])-1,m=parseInt(p[1])-1,v=parseInt(u[2])-1,w=parseInt(h[2])-1,g=parseInt(p[2])-1,T=t.c_verts.length/3,E=t.c_uvt.length/2,b=t.c_norms.length/3;if(A<0&&(A=T+A+1),d<0&&(d=T+d+1),f<0&&(f=T+f+1),I<0&&(I=E+I+1),y<0&&(y=E+y+1),m<0&&(m=E+m+1),v<0&&(v=b+v+1),w<0&&(w=b+w+1),g<0&&(g=b+g+1),t.i_verts.push(A,d,f),t.i_uvt.push(I,y,m),t.i_norms.push(v,w,g),5==r.length){var D=r[4].split("/"),P=parseInt(D[0])-1,R=parseInt(D[1])-1,C=parseInt(D[2])-1;P<0&&(P=T+P+1),R<0&&(R=E+R+1),C<0&&(C=b+C+1),t.i_verts.push(A,f,P),t.i_uvt.push(I,m,R),t.i_norms.push(v,g,C)}}}return s.to=t.i_verts.length,t},na.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},s={};s.ident=na.bin.ril(e,0),s.version=na.bin.ril(e,4),s.skinwidth=na.bin.ril(e,8),s.skinheight=na.bin.ril(e,12),s.framesize=na.bin.ril(e,16),s.num_skins=na.bin.ril(e,20),s.num_vertices=na.bin.ril(e,24),s.num_st=na.bin.ril(e,28),s.num_tris=na.bin.ril(e,32),s.num_glcmds=na.bin.ril(e,36),s.num_frames=na.bin.ril(e,40),s.offset_skins=na.bin.ril(e,44),s.offset_st=na.bin.ril(e,48),s.offset_tris=na.bin.ril(e,52),s.offset_frames=na.bin.ril(e,56),s.offset_glcmds=na.bin.ril(e,60),s.offset_end=na.bin.ril(e,64);var n=s.offset_st;t.c_uvt=[];for(var i=0;i<s.num_st;i++){var a=na.bin.rsl(e,n)/s.skinwidth,r=na.bin.rsl(e,n+2)/s.skinheight;t.c_uvt.push(a,r),n+=4}n=s.offset_tris;var l=[],o=[];t.i_verts=l,t.i_uvt=o;for(i=0;i<s.num_tris;i++)l.push(na.bin.rsl(e,n),na.bin.rsl(e,n+2),na.bin.rsl(e,n+4)),o.push(na.bin.rsl(e,n+6),na.bin.rsl(e,n+8),na.bin.rsl(e,n+10)),n+=12;n=s.offset_skins;t.skins=[];for(i=0;i<s.num_skins;i++)t.skins.push(na.bin.rASCII0(e,n)),n+=64;n=s.offset_frames;t.frames=[];var c=na.parse.fromMD2._normals;for(i=0;i<s.num_frames;i++){var u={},h=na.bin.rf(e,n),p=na.bin.rf(e,n+4),A=na.bin.rf(e,n+8);n+=12;var d=na.bin.rf(e,n),f=na.bin.rf(e,n+4),I=na.bin.rf(e,n+8);n+=12,u.name=na.bin.rASCII0(e,n),n+=16,u.verts=[],u.norms=[];for(var y=0;y<s.num_vertices;y++)u.verts.push(e[n]*h+d,e[n+1]*p+f,e[n+2]*A+I),u.norms.push(c[3*e[n+3]],c[3*e[n+3]+1],c[3*e[n+3]+2]),n+=4;t.frames.push(u)}return t},na.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],na.parse.fromCollada=function(e){var t=na.parse._buffToStr(e),s=(new DOMParser).parseFromString(t,"text/xml"),n={},i=(s=s.childNodes[0]).getElementsByTagName("asset")[0],a=s.getElementsByTagName("library_geometries")[0],r=s.getElementsByTagName("library_images")[0],l=s.getElementsByTagName("library_materials")[0],o=s.getElementsByTagName("library_effects")[0];return i&&(n.asset=na.parse.fromCollada._asset(i)),a&&(n.geometries=na.parse.fromCollada._libGeometries(a)),r&&(n.images=na.parse.fromCollada._libImages(r)),l&&(n.materials=na.parse.fromCollada._libMaterials(l)),o&&(n.effects=na.parse.fromCollada._libEffects(o)),n},na.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},na.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],s=0;s<e.length;s++){var n=e[s],i=na.parse.fromCollada._getMesh(n.getElementsByTagName("mesh")[0]);t.push(i)}return t},na.parse.fromCollada._getMesh=function(e){for(var t={},s=e.getElementsByTagName("source"),n=t.sources={},i=0;i<s.length;i++){for(var a=s[i].getElementsByTagName("float_array")[0].textContent.split(" "),r=a.length-(""==a[a.length-1]?1:0),l=new Array(r),o=0;o<r;o++)l[o]=parseFloat(a[o]);n[s[i].getAttribute("id")]=l}t.triangles=[];var c=e.getElementsByTagName("triangles");if(null==c)return t;for(i=0;i<c.length;i++){var u={},h=c[i];u.material=h.getAttribute("material");var p=h.getElementsByTagName("input"),A=[];for(o=0;o<p.length;o++){var d=p[o];l=[];A[parseInt(d.getAttribute("offset"))]=l;var f=d.getAttribute("semantic");u["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):d.getAttribute("source").substring(1),u["i_"+f]=l,n[u["s_"+f]]}var I=h.getElementsByTagName("p")[0].textContent.split(" "),y=3*Math.floor(I.length/3);for(o=0;o<y;o++)A[o%p.length].push(parseInt(I[o]));t.triangles.push(u)}return t},na.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("id")]=e[s].getElementsByTagName("init_from")[0].textContent;return t},na.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("name")]=e[s].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},na.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},s=0;s<e.length;s++){for(var n={},i=e[s].getElementsByTagName("newparam"),a=0;a<i.length;a++){var r=i[a].getElementsByTagName("surface")[0];r&&(n.surface=r.getElementsByTagName("init_from")[0].textContent)}t[e[s].getAttribute("id")]=n}return t},na.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=na.bin.rsl(e,0))return null;for(var s=na.bin.ril(e,2),n=6;n<s;){var i=na.bin.rsl(e,n),a=na.bin.ril(e,n+2);15677==i&&(t.edit=na.parse.from3DS._edit3ds(e,n,a)),45056==i&&(t.keyf=na.parse.from3DS._keyf3ds(e,n,a)),n+=a}return t},na.parse.from3DS._edit3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);16384==a&&(null==n.objects&&(n.objects=[]),n.objects.push(na.parse.from3DS._edit_object(e,i,r))),i+=r}return n},na.parse.from3DS._keyf3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);45058==a&&(null==n.desc&&(n.desc=[]),n.desc.push(na.parse.from3DS._keyf_objdes(e,i,r))),i+=r}return n},na.parse.from3DS._keyf_objdes=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);45072==a&&(n.hierarchy=na.parse.from3DS._keyf_objhierarch(e,i,r)),45073==a&&(n.dummy_name=na.bin.rASCII0(e,i+6)),i+=r}return n},na.parse.from3DS._keyf_objhierarch=function(e,t,s){var n={},i=t+6;return n.name=na.bin.rASCII0(e,i),i+=n.name.length+1,n.hierarchy=na.bin.rsl(e,i+4),n},na.parse.from3DS._edit_object=function(e,t,s){var n={},i=t+6;for(n.name=na.bin.rASCII0(e,i),i+=n.name.length+1;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);16640==a&&(n.mesh=na.parse.from3DS._obj_trimesh(e,i,r)),i+=r}return n},na.parse.from3DS._obj_trimesh=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);16656==a&&(n.vertices=na.parse.from3DS._tri_vertexl(e,i,r)),16672==a&&(n.indices=na.parse.from3DS._tri_facel1(e,i,r)),16704==a&&(n.uvt=na.parse.from3DS._tri_mappingcoors(e,i,r)),16736==a&&(n.local=na.parse.from3DS._tri_local(e,i,r)),i+=r}return n},na.parse.from3DS._tri_vertexl=function(e,t,s){var n=[],i=t+6,a=na.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(na.bin.rf(e,i)),n.push(na.bin.rf(e,i+4)),n.push(na.bin.rf(e,i+8)),i+=12;return n},na.parse.from3DS._tri_facel1=function(e,t,s){var n=[],i=t+6,a=na.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(na.bin.rsl(e,i)),n.push(na.bin.rsl(e,i+2)),n.push(na.bin.rsl(e,i+4)),i+=8;return n},na.parse.from3DS._tri_mappingcoors=function(e,t,s){var n=[],i=t+6,a=na.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(na.bin.rf(e,i)),n.push(1-na.bin.rf(e,i+4)),i+=8;return n},na.parse.from3DS._tri_local=function(e,t,s){var n={},i=t+6;return n.X=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n.Y=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n.Z=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n.C=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n},na.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},s={};return s.id=na.bin.ril(e,0),s.verS=na.bin.ril(e,4),s.texS=na.bin.ril(e,8),s.indS=na.bin.ril(e,12),s.verO=na.bin.ril(e,16),s.verL=na.bin.ril(e,20),s.texO=na.bin.ril(e,24),s.texL=na.bin.ril(e,28),s.indO=na.bin.ril(e,32),s.indL=na.bin.ril(e,36),0!=s.verO&&(t.vertices=na.parse.fromBIV._readFloats(e,s.verO,s.verL)),0!=s.texO&&(t.uvt=na.parse.fromBIV._readFloats(e,s.texO,s.texL)),0!=s.indO&&(t.indices=na.parse.fromBIV._readInts(e,s.indO,s.indL,s.indS)),t},na.parse.toBIV=function(e){for(var t=0,s=0;s<e.indices.length;s++)t=Math.max(t,e.indices[s]);var n=32;t<=65535&&(n=16);var i=40;e.vertices&&(i+=4*e.vertices.length),e.uvt&&(i+=4*e.uvt.length),e.indices&&(i+=e.indices.length*n/8);var a=new Uint8Array(i);na.bin.wil(a,0,1769365870),na.bin.wil(a,4,32),na.bin.wil(a,8,32),na.bin.wil(a,12,n);var r=40;return e.vertices&&(na.bin.wil(a,16,r),na.bin.wil(a,20,4*e.vertices.length),na.parse.fromBIV._writeFloats(a,r,e.vertices),r+=4*e.vertices.length),e.uvt&&(na.bin.wil(a,24,r),na.bin.wil(a,28,4*e.uvt.length),na.parse.fromBIV._writeFloats(a,r,e.uvt),r+=4*e.uvt.length),e.indices&&(na.bin.wil(a,32,r),na.bin.wil(a,36,4*e.indices.length),na.parse.fromBIV._writeInts(a,r,e.indices,n)),a.buffer},na.parse.fromBIV._readFloats=function(e,t,s){for(var n=[],i=0;i<s/4;i++)n.push(na.bin.rf(e,t+4*i));return n},na.parse.fromBIV._writeFloats=function(e,t,s){for(var n=0;n<s.length;n++)na.bin.wf(e,t+4*n,s[n])},na.parse.fromBIV._readInts=function(e,t,s,n){for(var i=[],a=0;a<s/4;a++)16==n&&i.push(na.bin.rsl(e,t+2*a)),32==n&&i.push(na.bin.ril(e,t+4*a));return i},na.parse.fromBIV._writeInts=function(e,t,s,n){for(var i=0;i<s.length;i++)16==n&&na.bin.wsl(e,t+2*i,s[i]),32==n&&na.bin.wil(e,t+4*i,s[i])},na.gen={},na.gen.Plane=function(e,t,s,n){s||(s=1),n||(n=1);for(var i={verts:[],inds:[],uvt:[]},a=e+1,r=t+1,l=0;l<r;l++)for(var o=0;o<a;o++){var c=o*(2/e)-1,u=l*(2/t)-1;i.verts.push(c,u,0),i.uvt.push(s*o/e,n*l/t),l<t&&o<e&&i.inds.push(l*a+o,l*a+o+1,(l+1)*a+o,l*a+o+1,(l+1)*a+o,(l+1)*a+o+1)}return i},na.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},na.gen.Sphere=function(e,t){for(var s={verts:[],inds:[],uvt:[]},n=e+1,i=t+1,a=0;a<i;a++)for(var r=0;r<n;r++){var l=-Math.PI/2+a*Math.PI/t,o=2*r*Math.PI/e,c=Math.cos(l)*Math.cos(o),u=Math.sin(l),h=Math.cos(l)*Math.sin(o);s.verts.push(c,u,h),s.uvt.push(r/e,a/t),a<t&&r<e&&s.inds.push(n*a+r,n*a+r+1,n*(a+1)+r,n*a+r+1,n*(a+1)+r,n*(a+1)+r+1)}return s},na.mat={},na.mat.scale=function(e,t,s){return[e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1]},na.mat.translate=function(e,t,s){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1]},na.mat.rotateDeg=function(e,t,s){var n=Math.PI/180;return na.mat.rotate(e*n,t*n,s*n)},na.mat.rotate=function(e,t,s){var n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i=e,a=t,r=s,l=Math.cos(i),o=Math.cos(a),c=Math.cos(r),u=Math.sin(i),h=Math.sin(a),p=Math.sin(r);return n[0]=o*c,n[1]=-o*p,n[2]=h,n[4]=l*p+u*h*c,n[5]=l*c-u*h*p,n[6]=-u*o,n[8]=u*p-l*h*c,n[9]=u*c+l*h*p,n[10]=l*o,n},na.edit={},na.edit.interpolate=function(e,t,s,n){for(var i=0;i<e.length;i++)s[i]=e[i]+n*(t[i]-e[i])},na.edit.transform=function(e,t){for(var s=0;s<e.length;s+=3){var n=e[s],i=e[s+1],a=e[s+2];e[s+0]=t[0]*n+t[4]*i+t[8]*a+t[12],e[s+1]=t[1]*n+t[5]*i+t[9]*a+t[13],e[s+2]=t[2]*n+t[6]*i+t[10]*a+t[14]}},na.edit.unwrap=function(e,t,s){for(var n=new Array(Math.floor(e.length/3)*s),i=0;i<e.length;i++)for(var a=0;a<s;a++)n[i*s+a]=t[e[i]*s+a];return n},na.edit.remap=function(e,t,s,n){for(var i=new Array(s.length),a=0;a<e.length;a++)for(var r=0;r<n;r++)i[t[a]*n+r]=s[e[a]*n+r];return i},na.utils={},na.utils.getAABB=function(e){var t,s,n,i,a,r;i=a=r=-(t=s=n=999999999);for(var l=0;l<e.length;l+=3){var o=e[l+0],c=e[l+1],u=e[l+2];o<t&&(t=o),o>i&&(i=o),c<s&&(s=c),c>a&&(a=c),u<n&&(n=u),c>r&&(r=u)}return{min:{x:t,y:s,z:n},max:{x:i,y:a,z:r}}};class ua extends _{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=p.vec3(t.pos||[0,0,0]),this._up=p.vec3(t.up||[0,1,0]),this._normal=p.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=p.vec3(),this._rtcPos=p.vec3(),this._imageSize=p.vec2(),this._texture=new Zi(this),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Mi(this,{matrix:p.inverseMat4(p.lookAtMat4v(this._pos,p.subVec3(this._pos,this._normal,p.mat4()),this._up,p.mat4())),children:[this._bitmapMesh=new vi(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Rt(this,oa({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new St(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height*e,1,this._height]}}class ha extends _{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],this._origin=p.vec3(t.origin||[0,0,0]),t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._mesh=new vi(this,{visible:t.visible,clippable:t.clippable,collidable:t.collidable,geometry:new sa(this,{primitive:"lines",positions:this._positions,indices:this._indices,origin:t.origin}),material:new St(this,{diffuse:t.color||[0,0,0],emissive:t.color||[0,0,0]})}),this.scene._lineSetCreated(this)}set visible(e){this._mesh.visible=e}get visible(){return this._mesh.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}const pa=p.vec3(),Aa=p.vec3(),da=p.vec3(),fa=p.vec3();class Ia extends r{constructor(e,t={}){super("BCFViewpoints",e,t),this.originatingSystem=t.originatingSystem||"xeokit.io",this.authoringTool=t.authoringTool||"xeokit.io"}getViewpoint(e={}){const t=this.viewer.scene,s=t.camera,n=t.realWorldOffset,i=!0===e.reverseClippingPlanes;let a={},r=p.normalizeVec3(p.subVec3(s.look,s.eye,p.vec3())),l=s.eye,o=s.up;s.yUp&&(r=va(r),l=va(l),o=va(o));const c=ya(p.addVec3(l,n));"ortho"===s.projection?a.orthogonal_camera={camera_view_point:c,camera_direction:ya(r),camera_up_vector:ya(o),view_to_world_scale:s.ortho.scale}:a.perspective_camera={camera_view_point:c,camera_direction:ya(r),camera_up_vector:ya(o),field_of_view:s.perspective.fov};const u=t.sectionPlanes;for(let e in u)if(u.hasOwnProperty(e)){let t=u[e];if(!t.active)continue;let r,l=t.pos;r=i?p.negateVec3(t.dir,p.vec3()):t.dir,s.yUp&&(l=va(l),r=va(r)),p.addVec3(l,n),l=ya(l),r=ya(r),a.clipping_planes||(a.clipping_planes=[]),a.clipping_planes.push({location:l,direction:r})}const h=t.lineSets;for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];a.lines||(a.lines=[]);const s=t.positions,n=t.indices;for(let e=0,t=n.length/2;e<t;e++){const t=n[2*e],i=n[2*e+1];a.lines.push({start_point:{x:s[3*t+0],y:s[3*t+1],z:s[3*t+2]},end_point:{x:s[3*i+0],y:s[3*i+1],z:s[3*i+2]}})}}const A=t.bitmaps;for(let e in A)if(A.hasOwnProperty(e)){let t=A[e],i=t.pos,r=t.normal,l=t.up;s.yUp&&(i=va(i),r=va(r),l=va(l)),p.addVec3(i,n),a.bitmaps||(a.bitmaps=[]),a.bitmaps.push({bitmap_type:t.type,bitmap_data:t.imageData,location:ya(i),normal:ya(r),up:ya(l),height:t.height})}a.components={visibility:{view_setup_hints:{spaces_visible:!!e.spacesVisible,space_boundaries_visible:!!e.spaceBoundariesVisible,openings_visible:!!e.openingsVisible}}};const d=new Set(t.opacityObjectIds),f=new Set(t.xrayedObjectIds),I=new Set(t.colorizedObjectIds),y=Object.values(t.objects).filter((e=>d.has(e.id)||I.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let n,i=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(s.colorize);s.xrayed?(n=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,n=Math.round(255*n).toString(16).padStart(2,"0"),i=n+i):d.has(s.id)&&(n=Math.round(255*s.opacity).toString(16).padStart(2,"0"),i=n+i),e[i]||(e[i]=[]);const a=s.id,r=s.originalSystemId,l={ifc_guid:r,originating_system:this.originatingSystem};return r!==a&&(l.authoring_tool_id=a),e[i].push(l),e}),{}),m=Object.entries(y).map((([e,t])=>({color:e,components:t})));a.components.coloring=m;const v=t.objectIds,w=t.visibleObjects,g=t.visibleObjectIds,T=v.filter((e=>!w[e])),E=t.selectedObjectIds;return e.defaultInvisible||g.length<T.length?(a.components.visibility.exceptions=this._createBCFComponents(g),a.components.visibility.default_visibility=!1):(a.components.visibility.exceptions=this._createBCFComponents(T),a.components.visibility.default_visibility=!0),a.components.selection=this._createBCFComponents(E),!1!==e.snapshot&&(a.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),a}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let n=0,i=e.length;n<i;n++){const i=e[n],a=t.objects[i];if(a){const e={ifc_guid:a.originalSystemId,originating_system:this.originatingSystem};a.originalSystemId!==i&&(e.authoring_tool_id=i),s.push(e)}}return s}setViewpoint(e,t={}){if(!e)return;const s=this.viewer,n=s.scene,i=n.camera,a=!1!==t.rayCast,r=!1!==t.immediate,l=!1!==t.reset,o=n.realWorldOffset,c=!0===t.reverseClippingPlanes;if(n.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.forEach((function(e){let t=ma(e.location,pa),s=ma(e.direction,pa);c&&p.negateVec3(s),p.subVec3(t,o),i.yUp&&(t=wa(t),s=wa(s)),new Pi(n,{pos:t,dir:s})})),n.clearLines(),e.lines){const t=[],s=[];let i=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),s.push(i++),s.push(i++))})),new ha(n,{positions:t,indices:s,clippable:!1,collidable:!0})}if(n.clearBitmaps(),e.bitmaps&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let a=ma(e.location,Aa),r=ma(e.normal,da),l=ma(e.up,fa),o=e.height||1;t&&s&&a&&r&&l&&(i.yUp&&(a=wa(a),r=wa(r),l=wa(l)),new ua(n,{src:s,type:t,pos:a,normal:r,up:l,clippable:!1,collidable:!0,height:o}))})),l&&(n.setObjectsXRayed(n.xrayedObjectIds,!1),n.setObjectsHighlighted(n.highlightedObjectIds,!1),n.setObjectsSelected(n.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(n.setObjectsVisible(n.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(n.setObjectsVisible(n.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const i=e.components.visibility.view_setup_hints;i&&(!1===i.spaces_visible&&n.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===i.openings_visible&&n.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!1),i.space_boundaries_visible)}e.components.selection&&(n.setObjectsSelected(n.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,n=0,i=!1;8===s.length&&(n=parseInt(s.substring(0,2),16)/256,n<=1&&n>=.95&&(n=1),s=s.substring(2),i=!0);const a=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=a,i&&(e.opacity=n)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let l,c,u,h;if(e.perspective_camera?(l=ma(e.perspective_camera.camera_view_point,pa),c=ma(e.perspective_camera.camera_direction,pa),u=ma(e.perspective_camera.camera_up_vector,pa),i.perspective.fov=e.perspective_camera.field_of_view,h="perspective"):(l=ma(e.orthogonal_camera.camera_view_point,pa),c=ma(e.orthogonal_camera.camera_direction,pa),u=ma(e.orthogonal_camera.camera_up_vector,pa),i.ortho.scale=e.orthogonal_camera.view_to_world_scale,h="ortho"),p.subVec3(l,o),i.yUp&&(l=wa(l),c=wa(c),u=wa(u)),a){const e=n.pick({pickSurface:!0,origin:l,direction:c});c=e?e.worldPos:p.addVec3(l,c,pa)}else c=p.addVec3(l,c,pa);r?(i.eye=l,i.look=c,i.up=u,i.projection=h):s.cameraFlight.flyTo({eye:l,look:c,up:u,duration:t.duration,projection:h})}}_withBCFComponent(e,t,s){const n=this.viewer,i=n.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const a=t.authoring_tool_id,r=i.objects[a];if(r)return void s(r);if(e.updateCompositeObjects){if(n.metaScene.metaObjects[a])return void i.withObjects(n.metaScene.getObjectIDsInSubtree(a),s)}}if(t.ifc_guid){const a=t.ifc_guid,r=i.objects[a];if(r)return void s(r);if(e.updateCompositeObjects){if(n.metaScene.metaObjects[a])return void i.withObjects(n.metaScene.getObjectIDsInSubtree(a),s)}Object.keys(i.models).forEach((t=>{const r=p.globalizeObjectId(t,a),l=i.objects[r];if(l)s(l);else if(e.updateCompositeObjects){n.metaScene.metaObjects[r]&&i.withObjects(n.metaScene.getObjectIDsInSubtree(r),s)}}))}}destroy(){super.destroy()}}function ya(e){return{x:e[0],y:e[1],z:e[2]}}function ma(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function va(e){return new Float64Array([e[0],-e[2],e[1]])}function wa(e){return new Float64Array([e[0],e[2],-e[1]])}var ga=p.vec3();const Ta=(e,t,s,n)=>{var i=e-s,a=t-n;return Math.sqrt(i*i+a*a)};class Ea extends _{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new q(s,t.origin),this._targetMarker=new q(s,t.target),this._originWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new Z(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new Z(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthWire=new J(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisWire=new J(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisWire=new J(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisWire=new J(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthLabel=new $(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisLabel=new $(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisLabel=new $(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisLabel=new $(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var n=this._pp,i=this._cp,a=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var r=a.top-t.top,l=a.left-t.left,o=e.canvas.boundary,c=o[2],u=o[3],h=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,I=s.units,y=s.unitsInfo[I].abbrev;for(var A=0,d=n.length;A<d;A+=4)i[h]=l+Math.floor((1+n[A+0]/n[A+3])*c/2),i[h+1]=r+Math.floor((1-n[A+1]/n[A+3])*u/2),h+=2;if(this._originDot.setPos(i[0],i[1]),this._targetDot.setPos(i[6],i[7]),this._lengthWire.setStartAndEnd(i[0],i[1],i[6],i[7]),this._xAxisWire.setStartAndEnd(i[0],i[1],i[2],i[3]),this._yAxisWire.setStartAndEnd(i[2],i[3],i[4],i[5]),this._zAxisWire.setStartAndEnd(i[4],i[5],i[6],i[7]),this.labelsVisible){this._lengthLabel.setPosOnWire(i[0],i[1],i[6],i[7]),this._xAxisLabel.setPosOnWire(i[0],i[1],i[2],i[3]),this._yAxisLabel.setPosOnWire(i[2],i[3],i[4],i[5]),this._zAxisLabel.setPosOnWire(i[4],i[5],i[6],i[7]);const e=this._approximate?" ~ ":" = ";this._length=Math.abs(p.lenVec3(p.subVec3(this._targetWorld,this._originWorld,ga))),this._lengthLabel.setText(e+(this._length*f).toFixed(2)+y);const t=Math.abs(Ta(i[0],i[1],i[2],i[3])),s=Math.abs(Ta(i[2],i[3],i[4],i[5])),n=Math.abs(Ta(i[4],i[5],i[6],i[7])),a=this.plugin.labelMinAxisLength;this._xAxisLabelCulled=t<a,this._yAxisLabelCulled=s<a,this._zAxisLabelCulled=n<a,this._xAxisLabelCulled?this._xAxisLabel.setCulled(!0):(this._xAxisLabel.setText(e+Math.abs((this._targetWorld[0]-this._originWorld[0])*f).toFixed(2)+y),this._xAxisLabel.setCulled(!this.axisVisible)),this._yAxisLabelCulled?this._yAxisLabel.setCulled(!0):(this._yAxisLabel.setText(e+Math.abs((this._targetWorld[1]-this._originWorld[1])*f).toFixed(2)+y),this._yAxisLabel.setCulled(!this.axisVisible)),this._zAxisLabelCulled?this._zAxisLabel.setCulled(!0):(this._zAxisLabel.setText(e+Math.abs((this._targetWorld[2]-this._originWorld[2])*f).toFixed(2)+y),this._zAxisLabel.setCulled(!this.axisVisible))}else this._lengthLabel.setCulled(!0),this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0);this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._xAxisWire.setVisible(this.axisVisible&&this.xAxisVisible),this._yAxisWire.setVisible(this.axisVisible&&this.yAxisVisible),this._zAxisWire.setVisible(this.axisVisible&&this.zAxisVisible),this._lengthWire.setVisible(this.wireVisible),this._lengthLabel.setCulled(!this.wireVisible),this._cpDirty=!1}}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get target(){return this._targetMarker}get length(){this._update();const e=this.plugin.viewer.scene.metrics.scale;return this._length*e}get color(){return this._color}set color(e){this._color=e,this._originDot.setFillColor(e),this._targetDot.setFillColor(e),this._lengthWire.setColor(e),this._lengthLabel.setFillColor(e)}set visible(e){e=void 0!==e?Boolean(e):this.plugin.defaultVisible,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._lengthWire.setVisible(this._visible&&this._wireVisible),this._lengthLabel.setVisible(this._visible&&this._wireVisible);const t=this._visible&&this._axisVisible&&this._xAxisVisible,s=this._visible&&this._axisVisible&&this._yAxisVisible,n=this._visible&&this._axisVisible&&this._zAxisVisible;this._xAxisWire.setVisible(t),this._yAxisWire.setVisible(s),this._zAxisWire.setVisible(n),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._yAxisLabel.setVisible(s&&!this._yAxisLabelCulled),this._zAxisLabel.setVisible(n&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultOriginVisible,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible)}get originVisible(){return this._originVisible}set targetVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultTargetVisible,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible)}get targetVisible(){return this._targetVisible}set axisEnabled(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisEnabled=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._xAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._xAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisEnabled(){return this._axisEnabled}set axisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisVisible=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._yAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._zAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisVisible(){return this._axisVisible}set xAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._xAxisVisible=e;const t=this._visible&&this._axisVisible&&this._xAxisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get xAxisVisible(){return this._xAxisVisible}set yAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._yAxisVisible=e;const t=this._visible&&this._axisVisible&&this._yAxisVisible&&this._axisEnabled;this._yAxisWire.setVisible(t),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get yAxisVisible(){return this._yAxisVisible}set zAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._zAxisVisible=e;const t=this._visible&&this._axisVisible&&this._zAxisVisible&&this._axisEnabled;this._zAxisWire.setVisible(t),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get zAxisVisible(){return this._zAxisVisible}set wireVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultWireVisible,this._wireVisible=e;var t=this._visible&&this._wireVisible;this._lengthLabel.setVisible(t),this._lengthWire.setVisible(t)}get wireVisible(){return this._wireVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._clickable&&this._axisEnabled),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._clickable&&this._axisEnabled),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._clickable&&this._axisEnabled),this._lengthLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._xAxisWire.setHighlighted(e),this._yAxisWire.setHighlighted(e),this._zAxisWire.setHighlighted(e),this._xAxisLabel.setHighlighted(e),this._yAxisLabel.setHighlighted(e),this._zAxisLabel.setHighlighted(e),this._lengthWire.setHighlighted(e),this._lengthLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._xAxisWire.setClickable(this._clickable),this._yAxisWire.setClickable(this._clickable),this._zAxisWire.setClickable(this._clickable),this._lengthWire.setClickable(this._clickable),this._xAxisLabel.setClickable(this._clickable),this._yAxisLabel.setClickable(this._clickable),this._zAxisLabel.setClickable(this._clickable),this._lengthLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene,t=e.metrics;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onMetricsUnits&&t.off(this._onMetricsUnits),this._onMetricsScale&&t.off(this._onMetricsScale),this._onMetricsOrigin&&t.off(this._onMetricsOrigin),this._originDot.destroy(),this._targetDot.destroy(),this._xAxisWire.destroy(),this._yAxisWire.destroy(),this._zAxisWire.destroy(),this._lengthLabel.destroy(),this._xAxisLabel.destroy(),this._yAxisLabel.destroy(),this._zAxisLabel.destroy(),this._lengthWire.destroy(),super.destroy()}}class ba{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const n=Da(e,s);return n?t?Pa(n,t):n:null}translatePlurals(e,t,s){const n=this._messages[this._locale];if(!n)return null;let i=Da(e,n);return i=0===(t=parseInt(""+t,10))?i.zero:t>1?i.other:i.one,i?(i=Pa(i,[t]),s&&(i=Pa(i,s)),i):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];if(n)for(const e in n)if(n.hasOwnProperty(e)){n[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let n=this._eventSubs[t];n||(n={},this._eventSubs[t]=n);const i=this._eventSubIDMap.addItem();n[i]={callback:s},this._eventSubEvents[i]=t;const a=this._events[t];return void 0!==a&&s(a),i}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function Da(e,t){if(t[e])return t[e];const s=e.split(".");let n=t;for(let e=0,t=s.length;n&&e<t;e++){n=n[s[e]]}return n}function Pa(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,s){return"{{"===e?"{":"}}"===e?"}":t[s]}))}class Ra extends _{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var s=e-t,n=e+t;s<0&&(s=0),n>1&&(n=1);var i=this.getPoint(s),a=this.getPoint(n),r=p.subVec3(a,i,[]);return p.normalizeVec3(r,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,s=[];for(t=0;t<=e;t++)s.push(this.getPoint(t/e));return s}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,s,n=[],i=this.getPoint(0),a=0;for(n.push(0),s=1;s<=e;s++)t=this.getPoint(s/e),a+=p.lenVec3(p.subVec3(t,i,[])),n.push(a),i=t;return this.cacheArcLengths=n,n}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var s,n=this._getLengths(),i=0,a=n.length;s=t||e*n[a-1];for(var r,l=0,o=a-1;l<=o;)if((r=n[i=Math.floor(l+(o-l)/2)]-s)<0)l=i+1;else{if(!(r>0)){o=i;break}o=i-1}if(n[i=o]===s)return i/(a-1);var c=n[i];return(i+(s-c)/(n[i+1]-c))/(a-1)}}class Ca extends Ra{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var s=(t.length-1)*e,n=Math.floor(s),i=s-n,a=t[0===n?n:n-1],r=t[n],l=t[n>t.length-2?t.length-1:n+1],o=t[n>t.length-3?t.length-1:n+2],c=p.vec3();return c[0]=p.catmullRomInterpolate(a[0],r[0],l[0],o[0],i),c[1]=p.catmullRomInterpolate(a[1],r[1],l[1],o[1],i),c[2]=p.catmullRomInterpolate(a[2],r[2],l[2],o[2],i),c}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const _a=p.vec3();class Ba extends _{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Ca(this),this._lookCurve=new Ca(this),this._upCurve=new Ca(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,s,n){const i={t:e,eye:t.slice(0),look:s.slice(0),up:n.slice(0)};this._frames.push(i),this._eyeCurve.points.push(i.eye),this._lookCurve.points.push(i.look),this._upCurve.points.push(i.up)}addFrames(e){let t;for(let s=0,n=e.length;s<n;s++)t=e[s],this.addFrame(t.t||0,t.eye,t.look,t.up)}loadFrame(e){const t=this.scene.camera;e=(e/=this._frames[this._frames.length-1].t-this._frames[0].t)<0?0:e>1?1:e,t.eye=this._eyeCurve.getPoint(e,_a),t.look=this._lookCurve.getPoint(e,_a),t.up=this._upCurve.getPoint(e,_a)}sampleFrame(e,t,s,n){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,s),this._upCurve.getPoint(e,n)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=p.vec3();var s=0;this._frames[0].t=0;const n=[];for(let e=1,a=this._frames.length;e<a;e++){var i=p.lenVec3(p.subVec3(this._frames[e].eye,this._frames[e-1].eye,t));n[e]=i,s+=i}for(let t=1,i=this._frames.length;t<i;t++){const i=n[t]/s*e;this._frames[t].t=this._frames[t-1].t+i}}clearFrames(){this._frames=[],this._eyeCurve.points=[],this._lookCurve.points=[],this._upCurve.points=[]}}const Oa=p.vec3(),Sa=p.vec3(),Na=p.vec3(),xa=p.vec3(),La=p.vec3();class Ma extends _{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=p.vec3(),this._eye1=p.vec3(),this._up1=p.vec3(),this._look2=p.vec3(),this._eye2=p.vec3(),this._up2=p.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,s){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=s;const n=this.scene.camera,i=!!e.projection&&e.projection!==n.projection;let a,r,l,o,c;if(this._eye1[0]=n.eye[0],this._eye1[1]=n.eye[1],this._eye1[2]=n.eye[2],this._look1[0]=n.look[0],this._look1[1]=n.look[1],this._look1[2]=n.look[2],this._up1[0]=n.up[0],this._up1[1]=n.up[1],this._up1[2]=n.up[2],this._orthoScale1=n.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)a=e.aabb;else if(6===e.length)a=e;else if(e.eye&&e.look||e.up)r=e.eye,l=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)l=e.look;else{let n=e;if((m.isNumeric(n)||m.isString(n))&&(c=n,n=this.scene.components[c],!n))return this.error("Component not found: "+m.inQuotes(c)),void(t&&(s?t.call(s):t()));i||(a=n.aabb||this.scene.aabb)}const u=e.poi;if(a){if(a[3]<a[0]||a[4]<a[1]||a[5]<a[2])return;if(a[3]===a[0]&&a[4]===a[1]&&a[5]===a[2])return;a=a.slice();const t=p.getAABB3Center(a);this._look2=u||t;const s=p.subVec3(this._eye1,this._look1,Oa),n=p.normalizeVec3(s),i=u?p.getAABB3DiagPoint(a,u):p.getAABB3Diag(a),r=e.fitFOV||this._fitFOV,l=Math.abs(i/Math.tan(r*p.DEGTORAD));this._orthoScale2=1.1*i,this._eye2[0]=this._look2[0]+n[0]*l,this._eye2[1]=this._look2[1]+n[1]*l,this._eye2[2]=this._look2[2]+n[2]*l,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(r||l||o)&&(this._flyingEyeLookUp=!!r&&!!l&&!!o,this._flyingEye=!!r&&!l,this._flyingLook=!!l&&!r,r&&(this._eye2[0]=r[0],this._eye2[1]=r[1],this._eye2[2]=r[2]),l&&(this._look2[0]=l[0],this._look2[1]=l[1],this._look2[2]=l[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));i?("ortho"===e.projection&&"ortho"!==n.projection&&(this._projection2="ortho",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.ortho.matrix.slice(),n.projection="customProjection"),"perspective"===e.projection&&"perspective"!==n.projection&&(this._projection2="perspective",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.perspective.matrix.slice(),n.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,R.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var s,n,i,a,r;if(e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye||e.look||e.up)i=e.eye,a=e.look,r=e.up;else{let t=e;if((m.isNumeric(t)||m.isString(t))&&(n=t,t=this.scene.components[n],!t))return void this.error("Component not found: "+m.inQuotes(n));s=t.aabb||this.scene.aabb}const l=e.poi;if(s){if(s[3]<=s[0]||s[4]<=s[1]||s[5]<=s[2])return;var o=l?p.getAABB3DiagPoint(s,l):p.getAABB3Diag(s);let n;a=l||p.getAABB3Center(s,a),this._trail?p.subVec3(t.look,a,La):p.subVec3(t.eye,t.look,La),p.normalizeVec3(La);n=(void 0!==e.fit?e.fit:this._fit)?Math.abs(o/Math.tan((e.fitFOV||this._fitFOV)*p.DEGTORAD)):p.lenVec3(p.subVec3(t.eye,t.look,Oa)),p.mulVec3Scalar(La,n),t.eye=p.addVec3(a,La,Oa),t.look=a,this.scene.camera.ortho.scale=1.1*o}else(i||a||r)&&(i&&(t.eye=i),a&&(t.look=a),r&&(t.up=r));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const s=this.easing?Ma._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(p.subVec3(n.eye,n.look,La),n.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,Na),n.look=p.subVec3(Na,La,Sa)):this._flyingLook&&(n.look=p.lerpVec3(s,0,1,this._look1,this._look2,Sa),n.up=p.lerpVec3(s,0,1,this._up1,this._up2,xa)):this._flyingEyeLookUp&&(n.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,Na),n.look=p.lerpVec3(s,0,1,this._look1,this._look2,Sa),n.up=p.lerpVec3(s,0,1,this._up1,this._up2,xa)),this._projection2){const t="ortho"===this._projection2?Ma._easeOutExpo(e,0,1,1):Ma._easeInCubic(e,0,1,1);n.customProjection.matrix=p.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();R.scheduleTask(this._update,this)}static _ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}static _easeInCubic(e,t,s,n){return s*(e/=n)*e*e+t}static _easeOutExpo(e,t,s,n){return s*(1-Math.pow(2,-10*e/n))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Fa extends _{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Ma(this),this._t=0,this.state=Fa.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const n=performance.now(),i=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==i)switch(this.state){case Fa.SCRUBBING:return;case Fa.PLAYING:if(this._t+=this._playingRate*i,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Fa.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Fa.PLAYING_TO:s=this._t+this._playingRate*i*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=Fa.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Fa.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Fa.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const n=s.frames[e];n?(this.state=Fa.SCRUBBING,this._cameraFlightAnimation.flyTo(n,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Fa.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Fa.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Fa.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Fa.STOPPED=0,Fa.SCRUBBING=1,Fa.PLAYING=2,Fa.PLAYING_TO=3;const Ha=p.vec3(),Ua=p.vec3();p.vec3();const Ga=p.vec3([0,-1,0]),Va=p.vec4([0,0,0,1]);class ja extends _{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=p.vec3(),this._origin=p.vec3(),this._rtcPos=p.vec3(),this._dir=p.vec3(),this._size=1,this._imageSize=p.vec2(),this._texture=new Zi(this),this._plane=new vi(this,{geometry:new Rt(this,oa({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new St(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new vi(this,{geometry:new Rt(this,la({size:1,divisions:10})),material:new St(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Mi(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),S(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,s=[-this._dir[0],-this._dir[1],-this._dir[2]];p.subVec3(t,this.position,Ha);const n=-p.dotVec3(s,Ha);p.normalizeVec3(s),p.mulVec3Scalar(s,n,Ua),p.vec3PairToQuaternion(Ga,e,Va),this._node.quaternion=Va}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],s=this._imageSize[1];if(t>s){const n=s/t;this._node.scale=[e,1,e*n]}else{const n=t/s;this._node.scale=[e*n,1,e]}}}class ka extends At{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const s=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const n=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=n.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=n.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new We({type:"point",pos:p.vec3([1,1,1]),color:p.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=p.identityMat4());const e=s._state.pos,t=n.look,i=n.up;p.lookAtMat4v(e,t,i,s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:()=>{if(s._shadowProjMatrixDirty){s._shadowProjMatrix||(s._shadowProjMatrix=p.identityMat4());const e=s.scene.canvas.canvas;p.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1}return s._shadowProjMatrix},getShadowRenderBuf:()=>(s._shadowRenderBuf||(s._shadowRenderBuf=new Ue(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function Qa(e){if(!Wa(e.width)||!Wa(e.height)){const t=document.createElement("canvas");t.width=za(e.width),t.height=za(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Wa(e){return 0==(e&e-1)}function za(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Ka extends _{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const s=this.scene.canvas.gl;this._state=new We({texture:new zi({gl:s,target:s.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),d.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,s=this.scene.canvas.gl;this._images=[];let n=!1,i=0;for(let a=0;a<e.length;a++){const r=new Image;r.onload=function(){let e=r;const l=a;return function(){if(!n&&(e=Qa(e),t._images[l]=e,i++,6===i)){let e=t._state.texture;e||(e=new zi({gl:s,target:s.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),r.onerror=function(){n=!0},r.src=e[a]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),d.memory.textures--,this._state.destroy()}}class Ya extends Ka{get type(){return"ReflectionMap"}constructor(e,t={}){super(e,t),this.scene._lightsState.addReflectionMap(this._state),this.scene._reflectionMapCreated(this)}destroy(){super.destroy(),this.scene._reflectionMapDestroyed(this)}}class Xa extends Ka{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}}class qa extends q{constructor(e,t={}){super(e,{entity:t.entity,occludable:t.occludable,worldPos:t.worldPos}),this._occluded=!1,this._visible=!0,this._src=null,this._image=null,this._pos=p.vec3(),this._origin=p.vec3(),this._rtcPos=p.vec3(),this._dir=p.vec3(),this._size=1,this._imageSize=p.vec2(),this._texture=new Zi(this,{src:t.src}),this._geometry=new Rt(this,{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),this._mesh=new vi(this,{geometry:this._geometry,material:new St(this,{ambient:[.9,.3,.9],shininess:30,diffuseMap:this._texture,backfaces:!0}),scale:[1,1,1],position:t.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),this.visible=!0,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,this.size=t.size,t.image?this.image=t.image:this.src=t.src}_setVisible(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,super._setVisible(e)}set visible(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}get visible(){return this._visible}set image(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],s=this._imageSize[1],n=s/t;this._geometry.positions=t>s?[e,e*n,0,-e,e*n,0,-e,-e*n,0,e,-e*n,0]:[e/n,e,0,-e/n,e,0,-e/n,-e,0,e/n,-e,0]}}class Ja{constructor(e){this._eye=p.vec3(),this._look=p.vec3(),this._up=p.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,s=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:s.fov,fovAxis:s.fovAxis,near:s.near,far:s.far};break;case"ortho":this._projection={projection:"ortho",scale:s.scale,near:s.near,far:s.far};break;case"frustum":this._projection={projection:"frustum",left:s.left,right:s.right,top:s.top,bottom:s.bottom,near:s.near,far:s.far};break;case"custom":this._projection={projection:"custom",matrix:s.matrix.slice()}}}restoreCamera(e,t){const s=e.camera,n=this._projection;function i(){switch(n.type){case"perspective":s.perspective.fov=n.fov,s.perspective.fovAxis=n.fovAxis,s.perspective.near=n.near,s.perspective.far=n.far;break;case"ortho":s.ortho.scale=n.scale,s.ortho.near=n.near,s.ortho.far=n.far;break;case"frustum":s.frustum.left=n.left,s.frustum.right=n.right,s.frustum.top=n.top,s.frustum.bottom=n.bottom,s.frustum.near=n.near,s.frustum.far=n.far;break;case"custom":s.customProjection.matrix=n.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:n.scale,projection:n.projection},(()=>{i(),t()})):(s.eye=this._eye,s.look=this._look,s.up=this._up,i(),s.projection=n.projection)}}const Za=p.vec3();class $a{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,s){const n=t.rootMetaObject;if(!n)return;const i=n.getObjectIDsInSubtree();this.numObjects=0,this._mask=s?m.apply(s,{}):null;const a=e.objects,r=!s||s.visible,l=!s||s.edges,o=!s||s.xrayed,c=!s||s.highlighted,u=!s||s.selected,h=!s||s.clippable,p=!s||s.pickable,A=!s||s.colorize,d=!s||s.opacity;for(var f=0,I=i.length;f<I;f++){const e=a[i[f]];if(e){if(r&&(this.objectsVisible[f]=e.visible),l&&(this.objectsEdges[f]=e.edges),o&&(this.objectsXrayed[f]=e.xrayed),c&&(this.objectsHighlighted[f]=e.highlighted),u&&(this.objectsSelected[f]=e.selected),h&&(this.objectsClippable[f]=e.clippable),p&&(this.objectsPickable[f]=e.pickable),A){const t=e.colorize;this.objectsColorize[3*f+0]=t[0],this.objectsColorize[3*f+1]=t[1],this.objectsColorize[3*f+2]=t[2]}d&&(this.objectsOpacity[f]=e.opacity),this.numObjects++}}}restoreObjects(e,t){const s=t.rootMetaObject;if(!s)return;const n=s.getObjectIDsInSubtree(),i=this._mask,a=!i||i.visible,r=!i||i.edges,l=!i||i.xrayed,o=!i||i.highlighted,c=!i||i.selected,u=!i||i.clippable,h=!i||i.pickable,p=!i||i.colorize,A=!i||i.opacity,d=e.objects;for(var f=0,I=n.length;f<I;f++){const e=d[n[f]];e&&(a&&(e.visible=this.objectsVisible[f]),r&&(e.edges=this.objectsEdges[f]),l&&(e.xrayed=this.objectsXrayed[f]),o&&(e.highlighted=this.objectsHighlighted[f]),c&&(e.selected=this.objectsSelected[f]),u&&(e.clippable=this.objectsClippable[f]),h&&(e.pickable=this.objectsPickable[f]),p&&(Za[0]=this.objectsColorize[3*f+0],Za[1]=this.objectsColorize[3*f+1],Za[2]=this.objectsColorize[3*f+2],e.colorize=Za),A&&(e.opacity=this.objectsOpacity[f]))}}}const er=p.vec3();class tr{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?m.apply(t,{}):null;const s=e.objects,n=!t||t.visible,i=!t||t.edges,a=!t||t.xrayed,r=!t||t.highlighted,l=!t||t.selected,o=!t||t.clippable,c=!t||t.pickable,u=!t||t.colorize,h=!t||t.opacity;for(let e in s)if(s.hasOwnProperty(e)){const t=s[e],p=this.numObjects;if(n&&(this.objectsVisible[p]=t.visible),i&&(this.objectsEdges[p]=t.edges),a&&(this.objectsXrayed[p]=t.xrayed),r&&(this.objectsHighlighted[p]=t.highlighted),l&&(this.objectsSelected[p]=t.selected),o&&(this.objectsClippable[p]=t.clippable),c&&(this.objectsPickable[p]=t.pickable),u){const e=t.colorize;e?(this.objectsColorize[3*p+0]=e[0],this.objectsColorize[3*p+1]=e[1],this.objectsColorize[3*p+2]=e[2],this.objectsHasColorize[p]=!0):this.objectsHasColorize[p]=!1}h&&(this.objectsOpacity[p]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,s=!t||t.visible,n=!t||t.edges,i=!t||t.xrayed,a=!t||t.highlighted,r=!t||t.selected,l=!t||t.clippable,o=!t||t.pickable,c=!t||t.colorize,u=!t||t.opacity;var h=0;const p=e.objects;for(let e in p)if(p.hasOwnProperty(e)){const t=p[e];s&&(t.visible=this.objectsVisible[h]),n&&(t.edges=this.objectsEdges[h]),i&&(t.xrayed=this.objectsXrayed[h]),a&&(t.highlighted=this.objectsHighlighted[h]),r&&(t.selected=this.objectsSelected[h]),l&&(t.clippable=this.objectsClippable[h]),o&&(t.pickable=this.objectsPickable[h]),c&&(this.objectsHasColorize[h]?(er[0]=this.objectsColorize[3*h+0],er[1]=this.objectsColorize[3*h+1],er[2]=this.objectsColorize[3*h+2],t.colorize=er):t.colorize=null),u&&(t.opacity=this.objectsOpacity[h]),h++}}}class sr extends Ra{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.v3=t.v3,this.t=t.t}set v0(e){this._v0=e||p.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||p.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||p.vec3([0,0,0])}get v2(){return this._v2}set v3(e){this.fire("v3",this._v3=e||p.vec3([0,0,0]))}get v3(){return this._v3}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=p.vec3();return t[0]=p.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=p.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=p.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class nr extends Ra{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,s,n;for(e=e||[],s=0,n=this._curves.length;s<n;s++)(t=this._curves[s]).off(this._dirtySubs[s]),t.off(this._destroyedSubs[s]);this._curves=[],this._dirtySubs=[],this._destroyedSubs=[];var i=this;function a(){i._dirty=!0}function r(){var e=this.id;for(s=0,n=i._curves.length;s<n;s++)if(i._curves[s].id===e)return i._curves=i._curves.slice(s,s+1),i._dirtySubs=i._dirtySubs.slice(s,s+1),i._destroyedSubs=i._destroyedSubs.slice(s,s+1),void(i._dirty=!0)}for(s=0,n=e.length;s<n;s++){if(t=e[s],m.isNumeric(t)||m.isString(t)){var l=t;if(!(t=this.scene.components[l])){this.error("Component not found: "+_inQuotes(l));continue}}var o=t.type;"xeokit.SplineCurve"===o||"xeokit.Path"===o||"xeokit.CubicBezierCurve"===o||"xeokit.QuadraticBezierCurve"===o?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",a)),this._destroyedSubs.push(t.once("destroyed",r))):this.error("Component "+_inQuotes(t.id)+" is not a xeokit.SplineCurve, xeokit.Path or xeokit.QuadraticBezierCurve")}this._dirty=!0}get curves(){return this._curves}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,s=e*this.length,n=this._getCurveLengths(),i=0;i<n.length;){if(n[i]>=s){var a=1-(n[i]-s)/(t=this._curves[i]).length;return t.getPointAt(a)}i++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],s=0,n=this._curves.length;for(e=0;e<n;e++)s+=this._curves[e].length,t.push(s);return this._cachedLengths=t,this._dirty=!1,t}_getJSON(){for(var e=[],t=0,s=this._curves.length;t<s;t++)e.push(this._curves[t].id);return{curves:e,t:this._t}}destroy(){var e,t,s;for(super.destroy(),e=0,t=this._curves.length;e<t;e++)(s=this._curves[e]).off(this._dirtySubs[e]),s.off(this._destroyedSubs[e])}}class ir extends Ra{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.t=t.t}set v0(e){this._v0=e||p.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||p.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||p.vec3([0,0,0])}get v2(){return this._v2}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=p.vec3();return t[0]=p.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=p.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=p.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class ar{constructor(e,t,s,n,i=null,a=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.aabb=null,this.layer=i,this.portionId=a,this._color=[s[0],s[1],s[2],n],this._colorize=[s[0],s[1],s[2],n],this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,n=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),n&&this.layer.setTransparent(this.portionId,t,s)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,n){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,s,n)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const rr=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let lr=0;const or={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},cr=new Float32Array([1,1,1,1]),ur=new Float32Array([0,0,0,1]),hr=p.vec4(),pr=p.vec3();class Ar{constructor(e,t=!1,{instancing:s=!1,edges:n=!1}={}){this._scene=e,this._withSAO=t,this._instancing=s,this._edges=n,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:s}=t.canvas,{model:n,layerIndex:i}=e,a=t._sectionPlanesState.sectionPlanes.length;if(a>0){const r=t._sectionPlanesState.sectionPlanes,l=i*a,o=n.renderFlags;for(let t=0;t<a;t++){const n=this._uSectionPlanes[t];if(n){const i=o.sectionPlanesActivePerLayer[l+t];if(s.uniform1i(n.active,i?1:0),i){const i=r[t],a=e._state.origin;if(a){const e=L(i.dist,i.dir,a,pr);s.uniform3fv(n.pos,e)}else s.uniform3fv(n.pos,i.pos);s.uniform3fv(n.dir,i.dir)}}}}}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uColor||(this._uColor=n.getLocation("silhouetteColor")),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uGammaFactor=n.getLocation("gammaFactor"),t.uniformBlockBinding(n.handle,t.getUniformBlockIndex(n.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=n.getLocation("zFar")),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)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aMetallicRoughness=n.getAttribute("metallicRoughness"),this._aFlags=n.getAttribute("flags"),this._aPickColor=n.getAttribute("pickColor"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrixCol0=n.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=n.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=n.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=n.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=n.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=n.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=n.getLocation("intensityRange")),this._uPointSize=n.getLocation("pointSize"),this._uNearPlaneHeight=n.getLocation("nearPlaneHeight")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState,a=i.lights,r=t.camera.project;n.bind(),e.textureUnit=0,this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[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;hr[0]=t,hr[1]=i,hr[2]=n.blendCutoff,hr[3]=n.blendFactor,s.uniform4fv(this._uSAOParams,hr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor),this._uPickInvisible&&s.uniform1i(this._uPickInvisible,e.pickInvisible),this._uShadowViewMatrix&&s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),this._uShadowProjMatrix&&s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix)}_makeVAO(e){const t=this._scene.canvas.gl,s=t.createVertexArray();return t.bindVertexArray(s),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer((this._instancing,e.positionsBuf)),this._aUV&&this._aUV.bindArrayBuffer((this._instancing,e.uvBuf)),this._aNormal&&this._aNormal.bindArrayBuffer((this._instancing,e.normalsBuf)),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer((e.colorsBuf,e.colorsBuf)),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),s}drawLayer(e,t,s,{colorUniform:n=!1,incrementDrawState:i=!1}={}){const a=pe.MAX_TEXTURE_IMAGE_UNITS,r=this._scene,l=r.canvas.gl,{_state:o,model:c}=t,{textureSet:u,origin:h,positionsDecodeMatrix:p}=o,A=r._lightsState,d=r.pointsMaterial,{camera:f}=c.scene,{viewNormalMatrix:I,project:y}=f,m=e.pickViewMatrix||f.viewMatrix,{worldMatrix:v,worldNormalMatrix:w}=c;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?l.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(o));let g=0;if(this._matricesUniformBlockBufferData.set(v,0),this._matricesUniformBlockBufferData.set(h?O(m,h):m,g+=16),this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,g+=16),this._matricesUniformBlockBufferData.set(p,g+=16),this._matricesUniformBlockBufferData.set(w,g+=16),this._matricesUniformBlockBufferData.set(I,g+=16),l.bindBuffer(l.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),l.bufferData(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,l.DYNAMIC_DRAW),l.bindBufferBase(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),l.uniform1i(this._uRenderPass,s),this.setSectionPlanesStateUniforms(t),r.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&l.uniform1f(this._uZFar,r.camera.project.far)}if(this._uPickInvisible&&l.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&l.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&l.uniform1f(this._uPickZFar,e.pickZFar),this._uPositionsDecodeMatrix&&l.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&l.uniformMatrix3fv(this._uUVDecodeMatrix,!1,(this._instancing,o.uvDecodeMatrix)),this._uIntensityRange&&d.filterIntensity&&l.uniform2f(this._uIntensityRange,d.minIntensity,d.maxIntensity),this._uPointSize&&l.uniform1f(this._uPointSize,d.pointSize),this._uNearPlaneHeight){const e="ortho"===r.camera.projection?1:l.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));l.uniform1f(this._uNearPlaneHeight,e)}if(u){const{colorTexture:t,metallicRoughnessTexture:s,emissiveTexture:n,normalsTexture:i,occlusionTexture:r}=u;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uMetallicRoughMap&&s&&(this._program.bindTexture(this._uMetallicRoughMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uEmissiveMap&&n&&(this._program.bindTexture(this._uEmissiveMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uNormalMap&&i&&(this._program.bindTexture(this._uNormalMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uAOMap&&r&&(this._program.bindTexture(this._uAOMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a)}if(A.reflectionMaps.length>0&&A.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,A.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),A.lightMaps.length>0&&A.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,A.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),this._withSAO){const t=r.sao;if(t.possible){const s=l.drawingBufferWidth,n=l.drawingBufferHeight;hr[0]=s,hr[1]=n,hr[2]=t.blendCutoff,hr[3]=t.blendFactor,l.uniform4fv(this._uSAOParams,hr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++}}if(n){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===or[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=r.xrayMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===or[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=r.highlightMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===or[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=r.selectedMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else l.uniform4fv(this._uColor,this._edges?ur:cr)}this._draw({state:o,frameCtx:e,incrementDrawState:i}),l.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class dr extends Ar{constructor(e,t,{instancing:s=!1,edges:n=!1}={}){super(e,t,{instancing:s,edges:n})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=n.pickElementsCount||s.indicesBuf.numItems,a=n.pickElementsOffset?n.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,a),i&&n.drawElements++}}}class fr extends dr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Ir extends Ar{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++)}}class yr extends Ir{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class mr extends Ar{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),i&&n.drawArrays++}}class vr extends Ar{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),i&&n.drawArrays++}}class wr extends Ar{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),i&&n.drawElements++}}class gr extends Ar{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++}}class Tr extends dr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// Triangles batching draw vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;");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+";")));a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;");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(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 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("vFlags = flags;")),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("// Triangles batching 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;")),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Er extends dr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),n){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(i),i.push("uniform vec4 lightAmbient;");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];"ambient"!==s.type&&(i.push("uniform vec4 lightColor"+e+";"),"dir"===s.type&&i.push("uniform vec3 lightDir"+e+";"),"point"===s.type&&i.push("uniform vec3 lightPos"+e+";"),"spot"===s.type&&(i.push("uniform vec3 lightPos"+e+";"),i.push("uniform vec3 lightDir"+e+";")))}if(i.push("in vec4 vViewPosition;"),i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}i.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),i.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),i.push("float lambertian = 1.0;"),i.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),i.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),i.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];if("ambient"!==s.type){if("dir"===s.type)"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===s.type)"view"===s.space?i.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):i.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==s.type)continue;"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}i.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),i.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return i.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):i.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class br extends dr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching silhouette fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = vColor;"),a.push("}"),a}}class Dr extends fr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Pr extends fr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Rr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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("in float vFlags;");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 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vPickColor; "),n.push("}"),n}}class Cr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 batching 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("in float vFlags;");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 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class _r extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 batching pick normals 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("in float vFlags;");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 vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Br extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),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 batching occlusion 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Or extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching depth fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),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("in float vFlags;");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("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("const float shiftRight8 = 1.0 / 256.;"),n.push("vec4 packDepthToRGBA( const in float v ) {"),n.push(" vec4 r = vec4( fract( v * packFactors ), v );"),n.push(" r.yzw -= r.xyz * shiftRight8;"),n.push(" return r * packUpScale;"),n.push("}"),n.push("in vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&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}}class Sr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Nr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<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("in vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class xr extends dr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Triangles batching quality draw 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("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),a.push("vFragDepth = 1.0 + clipPos.w;")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Triangles batching quality draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),r.push("uniform sampler2D uAOMap;"),r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),r.push(" return surf_norm;"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("float aoFactor = texture(uAOMap, vUV).r;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Lr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 batching pick flat normals 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Mr extends dr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,n=e._sectionPlanesState,i=n.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching color texture fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),i){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(a),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("in vec4 vViewPosition;"),a.push("in vec4 vColor;"),a.push("in vec2 vUV;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.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("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?a.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):a.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),a.push("float opacity = color.a;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):a.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&a.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Fr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Tr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Tr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Er(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Er(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Mr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Mr(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new xr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new xr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new br(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Or(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Sr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Dr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Pr(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Rr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new _r(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Lr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Cr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Br(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Nr(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Hr={};class Ur{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Gr=p.mat4(),Vr=p.mat4();function jr(e,t,s){const n=e.length,i=new Uint16Array(n),a=t[0],r=t[1],l=t[2],o=t[3]-a,c=t[4]-r,u=t[5]-l,h=65525,A=h/o,d=h/c,f=h/u,I=e=>e>=0?e:0;for(let t=0;t<n;t+=3)i[t+0]=Math.floor(I(e[t+0]-a)*A),i[t+1]=Math.floor(I(e[t+1]-r)*d),i[t+2]=Math.floor(I(e[t+2]-l)*f);return p.identityMat4(Gr),p.translationMat4v(t,Gr),p.identityMat4(Vr),p.scalingMat4v([o/h,c/h,u/h],Vr),p.mulMat4(Gr,Vr,s),i}function kr(e,t){const s=e[0],n=e[1],i=e[2],a=e[3]-s,r=e[4]-n,l=e[5]-i,o=65525;return p.identityMat4(Gr),p.translationMat4v(e,Gr),p.identityMat4(Vr),p.scalingMat4v([a/o,r/o,l/o],Vr),p.mulMat4(Gr,Vr,t),t}function Qr(e,t,s){let n=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),i=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=n,t=i;e=(1-Math.abs(i))*(n>=0?1:-1),t=(1-Math.abs(n))*(i>=0?1:-1),n=e,i=t}return new Int8Array([Math[t](127.5*n+(n<0?-1:0)),Math[s](127.5*i+(i<0?-1:0))])}function Wr(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}const zr=p.vec3();class Kr{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;let c=a.eye;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const u=t.aabb,h=[p.safeInv(u[3]-u[0])*p.MAX_INT,p.safeInv(u[4]-u[1])*p.MAX_INT,p.safeInv(u[5]-u[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(h[0]),e.snapPickCoordinateScale[1]=p.safeInv(h[1]),e.snapPickCoordinateScale[2]=p.safeInv(h[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),e.pickViewMatrix&&(c=e.pickOrigin||c);const A=[c[0]-o[0],c[1]-o[1],c[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,h),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniform1i(this._uSolid,t.solid);const d=e.pickViewMatrix||a.viewMatrix,f=o?O(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),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 I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;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=L(s.dist,s.dir,o,zr);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.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0),l.indicesBuf.unbind()}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(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._uSolid=s.getLocation("solid"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform bool solid;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// VBO SnapBatchingDepthBufInitRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yr=p.vec3();class Xr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}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;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const c=t.aabb,u=[p.safeInv(c[3]-c[0])*p.MAX_INT,p.safeInv(c[4]-c[1])*p.MAX_INT,p.safeInv(c[5]-c[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(u[0]),e.snapPickCoordinateScale[1]=p.safeInv(u[1]),e.snapPickCoordinateScale[2]=p.safeInv(u[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());let h=a.eye;e.pickViewMatrix&&(h=e.pickOrigin||h);const A=[h[0]-o[0],h[1]-o[1],h[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,u),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||a.viewMatrix,f=o?O(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),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 I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;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=L(s.dist,s.dir,o,Yr);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.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElements(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0),l.edgeIndicesBuf.unbind()):r.drawArrays(r.POINTS,0,l.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(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,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapBatchingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class qr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Kr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Xr(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Jr={};const Zr=p.mat4(),$r=p.mat4(),el=p.vec4([0,0,0,1]),tl=p.vec4([0,0,0,1]),sl=p.vec4([0,0,0,1]),nl=p.OBB3(),il=p.vec3(),al=p.vec3(),rl=p.vec3(),ll=p.vec3(),ol=p.vec3(),cl=p.vec3(),ul=p.vec3();class hl{constructor(e){console.log("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Hr[t];return s||(s=new Fr(e),Hr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Hr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=Jr[t];return s||(s=new qr(e),Jr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Jr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Ur(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new We({origin:p.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=p.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=p.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=p.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.normals,i=e.normalsCompressed,a=e.uv,r=e.uvCompressed,l=e.colors,o=e.colorsCompressed,c=e.indices,u=e.edgeIndices,h=e.color,A=e.metallic,d=e.roughness,f=e.opacity,I=e.meshMatrix,y=e.sceneModelMatrix,m=e.worldAABB,v=e.pickColor,w=this.model.scene,g=this._buffer,T=g.positions.length/3;let E;if(this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";E=s.length/3;for(let e=0,t=s.length;e<t;e++)g.positions.push(s[e]);const e=bt.getPositionsBounds(s),t=bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);m[0]=t[0],m[1]=t[1],m[2]=t[2],m[3]=n[0],m[4]=n[1],m[5]=n[2],y&&(p.AABB3ToOBB3(m,nl),p.transformOBB3(y,nl),p.OBB3ToAABB3(nl,m))}else{if(!t)throw"positions expected";E=t.length/3;const e=t.length,s=g.positions.length;for(let e=0,s=t.length;e<s;e++)g.positions.push(t[e]);if(I)for(let t=s,n=s+e;t<n;t+=3)el[0]=g.positions[t+0],el[1]=g.positions[t+1],el[2]=g.positions[t+2],p.transformPoint4(I,el,tl),g.positions[t+0]=tl[0],g.positions[t+1]=tl[1],g.positions[t+2]=tl[2],p.expandAABB3Point3(this._modelAABB,tl),y?(p.transformPoint4(y,tl,sl),p.expandAABB3Point3(m,sl)):p.expandAABB3Point3(m,tl);else for(let t=s,n=s+e;t<n;t+=3)el[0]=g.positions[t+0],el[1]=g.positions[t+1],el[2]=g.positions[t+2],p.expandAABB3Point3(this._modelAABB,el),y?(p.transformPoint4(y,el,tl),p.expandAABB3Point3(m,tl)):p.expandAABB3Point3(m,el)}if(this._state.origin){const e=this._state.origin;m[0]+=e[0],m[1]+=e[1],m[2]+=e[2],m[3]+=e[0],m[4]+=e[1],m[5]+=e[2]}if(p.expandAABB3(this.aabb,m),i&&i.length>0)for(let e=0,t=i.length;e<t;e++)g.normals.push(i[e]);else if(n&&n.length>0){const e=Zr;I?p.inverseMat4(p.transposeMat4(I,$r),e):p.identityMat4(e,e),function(e,t,s,n,i){function a(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let r,l,o,c,u,h,A=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(h=0;h<s;h+=3)A[0]=t[h],A[1]=t[h+1],A[2]=t[h+2],p.transformVec3(e,A,d),p.normalizeVec3(d,d),o=r=Qr(d,"floor","floor"),l=Wr(r),c=u=a(d,l),r=Qr(d,"ceil","floor"),l=Wr(r),c=a(d,l),c>u&&(o=r,u=c),r=Qr(d,"floor","ceil"),l=Wr(r),c=a(d,l),c>u&&(o=r,u=c),r=Qr(d,"ceil","ceil"),l=Wr(r),c=a(d,l),c>u&&(o=r,u=c),n[i+h+0]=o[0],n[i+h+1]=o[1],n[i+h+2]=0}(e,n,n.length,g.normals,g.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(255*l[e]),g.colors.push(255*l[e+1]),g.colors.push(255*l[e+2]),g.colors.push(255);else if(o)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(l[e]),g.colors.push(l[e+1]),g.colors.push(l[e+2]),g.colors.push(255);else if(h){const e=h[0],t=h[1],s=h[2],n=f;for(let i=0;i<E;i++)g.colors.push(e),g.colors.push(t),g.colors.push(s),g.colors.push(n)}const b=null!=A?A:0,D=null!=d?d:255;for(let e=0;e<E;e++)g.metallicRoughness.push(b),g.metallicRoughness.push(D);if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)g.uv.push(a[e]);else if(r&&r.length>0)for(let e=0,t=r.length;e<t;e++)g.uv.push(r[e]);for(let e=0,t=c.length;e<t;e++)g.indices.push(T+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)g.edgeIndices.push(T+u[e]);{const e=g.pickColors.length;for(let t=e,s=e+4*E;t<s;t+=4)g.pickColors.push(v[0]),g.pickColors.push(v[1]),g.pickColors.push(v[2]),g.pickColors.push(v[3])}if(w.entityOffsetsEnabled)for(let e=0;e<E;e++)g.offsets.push(0),g.offsets.push(0),g.offsets.push(0);const P=this._portions.length,R={vertsBaseIndex:T,numVerts:E,indicesBaseIndex:g.indices.length-c.length,numIndices:c.length};return w.pickSurfacePrecisionEnabled&&(R.indices=c,w.entityOffsetsEnabled&&(R.offset=new Float32Array(3))),this._portions.push(R),this._numPortions++,this.model.numPortions++,this._numVerts+=R.numVerts,P}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0){const n=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):jr(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=p.mat4());if(e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],s=3*t.vertsBaseIndex,i=s+3*t.numVerts;t.quantizedPositions=n.slice(s,i)}}if(s.normals.length>0){const n=new Int8Array(s.normals);let i=!0;e.normalsBuf=new De(t,t.ARRAY_BUFFER,n,s.normals.length,3,t.STATIC_DRAW,i)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.uv.length>0)if(e.uvDecodeMatrix){let n=!1;e.uvBuf=new De(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,n)}else{const n=bt.getUVBounds(s.uv),i=bt.compressUVs(s.uv,n.min,n.max),a=i.quantized;let r=!1;e.uvDecodeMatrix=p.mat3(i.decodeMatrix),e.uvBuf=new De(t,t.ARRAY_BUFFER,a,a.length,2,t.STATIC_DRAW,r)}if(s.metallicRoughness.length>0){const n=new Uint8Array(s.metallicRoughness);let i=!1;e.metallicRoughnessBuf=new De(t,t.ARRAY_BUFFER,n,s.metallicRoughness.length,2,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n),a=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const n=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,n,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,n=this._portions[s],i=4*n.vertsBaseIndex,a=4*n.numVerts,r=this._scratchMemory.getUInt8Array(a),l=t[0],o=t[1],c=t[2],u=t[3];for(let e=0;e<a;e+=4)r[e+0]=l,r[e+1]=o,r[e+2]=c,r[e+3]=u;this._state.colorsBuf&&this._state.colorsBuf.setData(r,i,a)}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){if(!this._finalized)throw"Not finalized";const i=e,a=this._portions[i],r=a.vertsBaseIndex,l=a.numVerts,o=!!(t&M),c=!!(t&V),u=!!(t&j),h=!!(t&k),p=!!(t&Q),A=!!(t&H),d=!!(t&F);let f,I;f=!o||d||c||u&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,I=!o||d?or.NOT_RENDERED:h?or.SILHOUETTE_SELECTED:u?or.SILHOUETTE_HIGHLIGHTED:c?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let y=0;y=!o||d?or.NOT_RENDERED:h?or.EDGES_SELECTED:u?or.EDGES_HIGHLIGHTED:c?or.EDGES_XRAYED:p?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let m=o&&!d&&A?or.PICK:or.NOT_RENDERED;const v=t&U?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=r,t=r+l;e<t;e++){let t=0;t|=f,t|=I<<4,t|=y<<8,t|=m<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(l);for(let t=0;t<l;t++){let s=0;s|=f,s|=I<<4,s|=y<<8,s|=m<<12,s|=v<<16,e[t]=s}this._state.flagsBuf.setData(e,r,l)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=e,n=this._portions[s],i=3*n.vertsBaseIndex,a=3*n.numVerts,r=this._scratchMemory.getFloat32Array(a),l=t[0],o=t[1],c=t[2];for(let e=0;e<a;e+=3)r[e+0]=l,r[e+1]=o,r[e+2]=c;this._state.offsetsBuf&&this._state.offsetsBuf.setData(r,i,a),this.model.scene.pickSurfacePrecisionEnabled&&(n.offset[0]=t[0],n.offset[1]=t[1],n.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return;const s=this._state,n=this._portions[e];if(!n)return void this.model.error("portion not found: "+e);const i=n.quantizedPositions,a=s.origin,r=n.offset,l=a[0]+r[0],o=a[1]+r[1],c=a[2]+r[2],u=el;for(let e=0,n=i.length;e<n;e+=3)u[0]=i[e],u[1]=i[e+1],u[2]=i[e+2],u[3]=1,p.decompressPosition(u,s.positionsDecodeMatrix),p.transformPoint4(this.model.worldMatrix,u),u[0]+=l,u[1]+=o,u[2]+=c,t(u)}getElementsCountAndOffset(e){let t=null,s=null;const n=this._portions[e];return n&&(t=n.numIndices,s=n.indicesBaseIndex),{count:t,offset:s}}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?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRendererWithSAO&&this._batchingRenderers.pbrRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRendererWithSAO&&this._batchingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._batchingRenderers.flatColorRendererWithSAO&&this._batchingRenderers.flatColorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||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),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,or.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._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,or.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._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsFlatRenderer&&this._batchingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,or.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthBufInitRenderer&&this._snapBatchingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,or.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthRenderer&&this._snapBatchingRenderers.snapDepthRenderer.drawLayer(t,this,or.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state,r=this._portions[e];if(!r)return this.model.error("portion not found: "+e),!1;const l=r.quantizedPositions,o=r.indices,c=a.origin,u=r.offset,h=il,A=al;h.set(c?p.subVec3(t,c,rl):t),A.set(s),u&&p.subVec3(h,u),p.transformRay(this.model.worldNormalMatrix,h,A,h,A);const d=ll,f=ol,I=cl;let y=!1,m=0;const v=ul;for(let e=0,s=o.length;e<s;e+=3){const s=3*o[e],r=3*o[e+1],w=3*o[e+2];if(d[0]=l[s],d[1]=l[s+1],d[2]=l[s+2],f[0]=l[r],f[1]=l[r+1],f[2]=l[r+2],I[0]=l[w],I[1]=l[w+1],I[2]=l[w+2],p.decompressPosition(d,a.positionsDecodeMatrix),p.decompressPosition(f,a.positionsDecodeMatrix),p.decompressPosition(I,a.positionsDecodeMatrix),p.rayTriangleIntersect(h,A,d,f,I,v)){p.transformPoint3(this.model.worldMatrix,v,v),u&&p.addVec3(v,u),c&&p.addVec3(v,c);const e=Math.abs(p.lenVec3(p.subVec3(v,t,[])));(!y||e>m)&&(m=e,n.set(v),i&&p.triangleNormal(d,f,I,i),y=!0)}}return y&&i&&(p.transformVec3(this.model.worldNormalMatrix,i,i),p.normalizeVec3(i)),y}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class pl extends Ir{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i,a,r;const l=[];for(l.push("#version 300 es"),l.push("// Instancing geometry drawing vertex shader"),l.push("uniform int renderPass;"),l.push("in vec3 position;"),l.push("in vec2 normal;"),l.push("in vec4 color;"),l.push("in float flags;"),e.entityOffsetsEnabled&&l.push("in vec3 offset;"),l.push("in vec4 modelMatrixCol0;"),l.push("in vec4 modelMatrixCol1;"),l.push("in vec4 modelMatrixCol2;"),l.push("in vec4 modelNormalMatrixCol0;"),l.push("in vec4 modelNormalMatrixCol1;"),l.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(l,!0),e.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;")),l.push("uniform vec4 lightAmbient;"),i=0,a=s.lights.length;i<a;i++)r=s.lights[i],"ambient"!==r.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===r.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===r.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===r.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")));for(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.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);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"),n&&(l.push("out vec4 vWorldPosition;"),l.push("out float vFlags;")),l.push("out vec4 vColor;"),l.push("void main(void) {"),l.push("int colorFlag = int(flags) & 0xF;"),l.push("if (colorFlag != renderPass) {"),l.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),l.push("} else {"),l.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),l.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&l.push(" worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix * worldPosition; "),l.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),l.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),l.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),i=0,a=s.lights.length;i<a;i++)if(r=s.lights[i],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}return l.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),l.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),l.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(l.push("vWorldPosition = worldPosition;"),l.push("vFlags = flags;")),l.push("gl_Position = clipPos;"),l.push("}"),l.push("}"),l}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Al extends Ir{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let n,i;const a=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry flat-shading drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),a){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];"ambient"!==e.type&&(r.push("uniform vec4 lightColor"+n+";"),"dir"===e.type&&r.push("uniform vec3 lightDir"+n+";"),"point"===e.type&&r.push("uniform vec3 lightPos"+n+";"),"spot"===e.type&&(r.push("uniform vec3 lightPos"+n+";"),r.push("uniform vec3 lightDir"+n+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),a){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}for(r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?r.push("viewLightDir = -normalize(lightPos"+n+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+n+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+n+".rgb * lightColor"+n+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class dl extends Ir{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing fill 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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class fl extends yr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Il extends yr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class yl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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("in float vFlags;");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 vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vPickColor; "),n.push("}"),n}}class ml extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 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("in float vFlags;");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 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 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class vl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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"),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("in float vFlags;");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 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class wl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),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("in float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("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("// Instancing occlusion 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class gl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry depth drawing fragment shader"),a.push("precision highp float;"),a.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec2 vHighPrecisionZW;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),a.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),a.push("}"),a}}class Tl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class El extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}const bl={3e3:"linearToLinear",3001:"sRGBToLinear"};class Dl extends Ir{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Instancing geometry quality drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push(" worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),a.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),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("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Instancing geometry quality drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),r.push(" return normalize(surf_norm );"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = "+bl[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = "+bl[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Pl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = 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"),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("in float vFlags;");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 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&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(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Rl extends Ir{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState;let i,a;const r=s.sectionPlanes.length>0,l=[];if(l.push("#version 300 es"),l.push("// Instancing geometry drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),e.logarithmicDepthBufferEnabled&&(l.push("in float isPerspective;"),l.push("uniform float logDepthBufFC;"),l.push("in float vFragDepth;")),l.push("uniform sampler2D uColorMap;"),this._withSAO&&(l.push("uniform sampler2D uOcclusionTexture;"),l.push("uniform vec4 uSAOParams;"),l.push("const float packUpscale = 256. / 255.;"),l.push("const float unpackDownScale = 255. / 256.;"),l.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),l.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),l.push("float unpackRGBToFloat( const in vec4 v ) {"),l.push(" return dot( v, unPackFactors );"),l.push("}")),l.push("uniform float gammaFactor;"),l.push("vec4 linearToLinear( in vec4 value ) {"),l.push(" return value;"),l.push("}"),l.push("vec4 sRGBToLinear( in vec4 value ) {"),l.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),l.push("}"),l.push("vec4 gammaToLinear( in vec4 value) {"),l.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),l.push("}"),t&&(l.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),r){l.push("in vec4 vWorldPosition;"),l.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("uniform bool sectionPlaneActive"+e+";"),l.push("uniform vec3 sectionPlanePos"+e+";"),l.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(l),l.push("uniform vec4 lightAmbient;"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];"ambient"!==e.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===e.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===e.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===e.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")))}if(l.push("in vec4 vViewPosition;"),l.push("in vec4 vColor;"),l.push("in vec2 vUV;"),l.push("out vec4 outColor;"),l.push("void main(void) {"),r){l.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),l.push(" if (clippable) {"),l.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("if (sectionPlaneActive"+e+") {"),l.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),l.push("}");l.push(" if (dist > 0.0) { "),l.push(" discard;"),l.push(" }"),l.push("}")}for(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),l.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),l.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),l.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}}return l.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?l.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):l.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),l.push("float opacity = color.a;"),this._withSAO?(l.push(" float viewportWidth = uSAOParams[0];"),l.push(" float viewportHeight = uSAOParams[1];"),l.push(" float blendCutoff = uSAOParams[2];"),l.push(" float blendFactor = uSAOParams[3];"),l.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),l.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb * ambient, opacity);")):l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb, opacity);"),t&&l.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&l.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),l.push("}"),l}}class Cl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new pl(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new pl(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Al(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Al(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Dl(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Dl(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Rl(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Rl(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new dl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new gl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Tl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new fl(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Il(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new yl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new vl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Pl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ml(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new wl(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new El(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const _l={};const Bl=p.vec3();class Ol{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.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[p.safeInv(o[3]-o[0])*p.MAX_INT,p.safeInv(o[4]-o[1])*p.MAX_INT,p.safeInv(o[5]-o[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(c[0]),e.snapPickCoordinateScale[1]=p.safeInv(c[1]),e.snapPickCoordinateScale[2]=p.safeInv(c[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let h=u.eye;e.pickViewMatrix&&(h=e.pickOrigin||h);const A=[h[0]-l[0],h[1]-l[1],h[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?O(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=L(s.dist,s.dir,l,Bl);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags&&(this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),r.indicesBuf.bind(),a.drawElementsInstanced(a.TRIANGLES,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),r.indicesBuf.unbind(),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Sl=p.vec3();class Nl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const n=t.model,i=n.scene,a=i.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[p.safeInv(o[3]-o[0])*p.MAX_INT,p.safeInv(o[4]-o[1])*p.MAX_INT,p.safeInv(o[5]-o[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(c[0]),e.snapPickCoordinateScale[1]=p.safeInv(c[1]),e.snapPickCoordinateScale[2]=p.safeInv(c[2]),!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let h=u.eye;e.pickViewMatrix&&(h=e.pickOrigin||h);const A=[h[0]-l[0],h[1]-l[1],h[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?O(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=L(s.dist,s.dir,l,Sl);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),"edge"===e.snapMode?(r.edgeIndicesBuf.bind(),a.drawElementsInstanced(a.LINES,r.edgeIndicesBuf.numItems,r.edgeIndicesBuf.itemType,0,r.numInstances),r.edgeIndicesBuf.unbind()):a.drawArraysInstanced(a.POINTS,0,r.positionsBuf.numItems,r.numInstances),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(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,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapInstancingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class xl{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Ol(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Nl(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Ll={};const Ml=new Uint8Array(4),Fl=new Float32Array(1),Hl=p.vec4([0,0,0,1]),Ul=p.vec4([0,0,0,1]),Gl=p.vec4([0,0,0,1]),Vl=new Float32Array(3),jl=p.vec3(),kl=p.vec3(),Ql=p.vec3(),Wl=p.vec3(),zl=p.vec3(),Kl=p.vec3(),Yl=p.vec3();class Xl{constructor(e){console.log("Creating TrianglesInstancingLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=_l[t];return s||(s=new Cl(e),_l[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete _l[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=Ll[t];return s||(s=new xl(e),Ll[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Ll[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new We({numInstances:0,obb:p.OBB3(),origin:p.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=p.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,n=e.roughness,i=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,a=e.meshMatrix,r=e.sceneModelMatrix,l=e.aabb,o=e.pickColor;if(this._finalized)throw"Already finalized";const c=t[0],u=t[1],h=t[2];if(this._colors.push(c),this._colors.push(u),this._colors.push(h),this._colors.push(i),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(a[0]),this._modelMatrixCol0.push(a[4]),this._modelMatrixCol0.push(a[8]),this._modelMatrixCol0.push(a[12]),this._modelMatrixCol1.push(a[1]),this._modelMatrixCol1.push(a[5]),this._modelMatrixCol1.push(a[9]),this._modelMatrixCol1.push(a[13]),this._modelMatrixCol2.push(a[2]),this._modelMatrixCol2.push(a[6]),this._modelMatrixCol2.push(a[10]),this._modelMatrixCol2.push(a[14]),this._state.geometry.normals){let e=p.transposeMat4(a,p.mat4()),t=p.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(o[0]),this._pickColors.push(o[1]),this._pickColors.push(o[2]),this._pickColors.push(o[3]);const A=this._state.geometry.positionsCompressed.length,d=this._state.geometry.positionsCompressed,f=this._state.geometry.positionsDecodeMatrix;for(let e=0;e<A;e+=3)Hl[0]=d[e+0],Hl[1]=d[e+1],Hl[2]=d[e+2],p.transformPoint4(f,Hl,Ul),p.transformPoint4(a,Ul,Hl),r?(p.transformPoint4(r,Hl,Gl),p.expandAABB3Point3(l,Gl)):p.expandAABB3Point3(l,Hl);if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}p.expandAABB3(this.aabb,l),this._state.numInstances++;const I=this._portions.length,y={};return this.model.scene.pickSurfacePrecisionEnabled&&(y.matrix=a.slice(),y.inverseMatrix=null,y.normalMatrix=null),this._portions.push(y),this._numPortions++,this.model.numPortions++,I}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,s=e.textureSet,n=this.model.scene.canvas.gl,i=this._colors.length,a=i/4;if(i>0){let t=!1;e.colorsBuf=new De(n,n.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,n.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new De(n,n.ARRAY_BUFFER,t,this._metallicRoughness.length,2,n.STATIC_DRAW,s)}if(a>0){let t=!1;e.flagsBuf=new De(n,n.ARRAY_BUFFER,new Float32Array(a),a,1,n.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,n.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new De(n,n.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,n.STATIC_DRAW,s),e.positionsDecodeMatrix=p.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),i=!1;e.colorsBuf=new De(n,n.ARRAY_BUFFER,s,s.length,4,n.STATIC_DRAW,i)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new De(n,n.ARRAY_BUFFER,s,s.length,2,n.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,n.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,n.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelMatrixCol1Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelMatrixCol2Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new De(n,n.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,n.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ml[0]=t[0],Ml[1]=t[1],Ml[2]=t[2],Ml[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Ml,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&M),i=!!(t&V),a=!!(t&j),r=!!(t&k),l=!!(t&Q),o=!!(t&H),c=!!(t&F);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,h=!n||c?or.NOT_RENDERED:r?or.SILHOUETTE_SELECTED:a?or.SILHOUETTE_HIGHLIGHTED:i?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let p=0;p=!n||c?or.NOT_RENDERED:r?or.EDGES_SELECTED:a?or.EDGES_HIGHLIGHTED:i?or.EDGES_XRAYED:l?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?or.PICK:or.NOT_RENDERED)<<12,A|=(t&U?1:0)<<16,Fl[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(Fl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Vl[0]=t[0],Vl[1]=t[1],Vl[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Vl,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,n=s.geometry,i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const a=n.quantizedPositions,r=s.origin,l=i.offset,o=r[0]+l[0],c=r[1]+l[1],u=r[2]+l[2],h=Hl,A=i.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=a.length;e<s;e+=3)h[0]=a[e],h[1]=a[e+1],h[2]=a[e+2],p.decompressPosition(h,f),p.transformPoint3(A,h),p.transformPoint3(d,h),h[0]+=o,h[1]+=c,h[2]+=u,t(h)}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?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRendererWithSAO&&this._instancingRenderers.pbrRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRendererWithSAO&&this._instancingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._instancingRenderers.flatColorRendererWithSAO&&this._instancingRenderers.flatColorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||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),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,or.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._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,or.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._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(t,this,or.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthBufInitRenderer&&this._snapInstancingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,or.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthRenderer&&this._snapInstancingRenderers.snapDepthRenderer.drawLayer(t,this,or.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state.geometry,r=this._state,l=this._portions[e];if(!l)return this.model.error("portion not found: "+e),!1;l.inverseMatrix||(l.inverseMatrix=p.inverseMat4(l.matrix,p.mat4())),i&&!l.normalMatrix&&(l.normalMatrix=p.transposeMat4(l.inverseMatrix,p.mat4()));const o=a.quantizedPositions,c=a.indices,u=r.origin,h=l.offset,A=jl,d=kl;A.set(u?p.subVec3(t,u,Ql):t),d.set(s),h&&p.subVec3(A,h),p.transformRay(this.model.worldNormalMatrix,A,d,A,d),p.transformRay(l.inverseMatrix,A,d,A,d);const f=Wl,I=zl,y=Kl;let m=!1,v=0;const w=Yl;for(let e=0,s=c.length;e<s;e+=3){const s=3*c[e+0],a=3*c[e+1],g=3*c[e+2];f[0]=o[s],f[1]=o[s+1],f[2]=o[s+2],I[0]=o[a],I[1]=o[a+1],I[2]=o[a+2],y[0]=o[g],y[1]=o[g+1],y[2]=o[g+2];const{positionsDecodeMatrix:T}=r.geometry;if(p.decompressPosition(f,T),p.decompressPosition(I,T),p.decompressPosition(y,T),p.rayTriangleIntersect(A,d,f,I,y,w)){p.transformPoint3(l.matrix,w,w),p.transformPoint3(this.model.worldMatrix,w,w),h&&p.addVec3(w,h),u&&p.addVec3(w,u);const e=Math.abs(p.lenVec3(p.subVec3(w,t,[])));(!m||e>v)&&(v=e,n.set(w),i&&p.triangleNormal(f,I,y,i),m=!0)}}return m&&i&&(p.transformVec3(l.normalMatrix,i,i),p.transformVec3(this.model.worldNormalMatrix,i,i),p.normalizeVec3(i)),m}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ql extends wr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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 n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Jl extends wr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Zl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ql(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jl(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const $l={};class eo{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const to=p.vec4([0,0,0,1]),so=p.vec4([0,0,0,1]),no=p.vec4([0,0,0,1]),io=p.OBB3();class ao{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=$l[t];return s||(s=new Zl(e),$l[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete $l[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new eo(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new We({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:p.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.indices,i=e.color,a=e.opacity,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB;e.pickColor;const c=this._buffer,u=c.positions.length/3;let h;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";h=s.length/3;for(let e=0,t=s.length;e<t;e++)c.positions.push(s[e]);const e=bt.getPositionsBounds(s),t=bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(p.AABB3ToOBB3(o,io),p.transformOBB3(l,io),p.OBB3ToAABB3(io,o))}else{if(!t)throw"positions expected";h=t.length/3;const e=t.length,s=c.positions.length;for(let e=0,s=t.length;e<s;e++)c.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)to[0]=c.positions[t+0],to[1]=c.positions[t+1],to[2]=c.positions[t+2],p.transformPoint4(r,to,so),c.positions[t+0]=so[0],c.positions[t+1]=so[1],c.positions[t+2]=so[2],p.expandAABB3Point3(this._modelAABB,so),l?(p.transformPoint4(l,so,no),p.expandAABB3Point3(o,no)):p.expandAABB3Point3(o,so);else for(let t=s,n=s+e;t<n;t+=3)to[0]=c.positions[t+0],to[1]=c.positions[t+1],to[2]=c.positions[t+2],p.expandAABB3Point3(this._modelAABB,to),l?(p.transformPoint4(l,to,so),p.expandAABB3Point3(o,so)):p.expandAABB3Point3(o,to)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(p.expandAABB3(this.aabb,o),i){const e=i[0],t=i[1],s=i[2],n=a;for(let i=0;i<h;i++)c.colors.push(e),c.colors.push(t),c.colors.push(s),c.colors.push(n)}if(n)for(let e=0,t=n.length;e<t;e++)c.indices.push(n[e]+u);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<h;e++)c.offsets.push(0),c.offsets.push(0),c.offsets.push(0);const A=this._portions.length/2;return this._portions.push(u),this._portions.push(h),this._numPortions++,this.model.numPortions++,this._numVerts+=h,A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=jr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.colors.length>0){const n=s.colors.length/4,i=new Float32Array(n);let a=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2],c=t[3];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o,a[e+3]=c;this._state.colorsBuf.setData(a,n,i)}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){if(!this._finalized)throw"Not finalized";const i=2*e,a=this._portions[i],r=this._portions[i+1],l=!!(t&M),o=!!(t&V),c=!!(t&j),u=!!(t&k),h=!!(t&H),p=!!(t&F);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,d=!l||p?or.NOT_RENDERED:u?or.SILHOUETTE_SELECTED:c?or.SILHOUETTE_HIGHLIGHTED:o?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let f=l&&!p&&h?or.PICK:or.NOT_RENDERED;const I=t&U?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=a,t=a+r;e<t;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(r);for(let t=0;t<r;t++){let s=0;s|=A,s|=d<<4,s|=f<<12,s|=I<<16,e[t]=s}this._state.flagsBuf.setData(e,a,r)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class ro extends gr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Lines instancing color fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class lo extends gr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class oo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ro(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new lo(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const co={};const uo=new Uint8Array(4),ho=new Float32Array(1),po=p.vec4([0,0,0,1]),Ao=p.vec4([0,0,0,1]),fo=p.vec4([0,0,0,1]),Io=new Float32Array(3);class yo{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=co[t];return s||(s=new oo(e),co[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete co[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new We({obb:p.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=p.vec3(e.origin)),this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,n=e.meshMatrix,i=e.worldMatrix,a=e.aabb;if(this._finalized)throw"Already finalized";const r=t[0],l=t[1],o=t[2];t[3],this._colors.push(r),this._colors.push(l),this._colors.push(o),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),p.collapseAABB3(a);const c=this._state.obb,u=c.length;for(let e=0;e<u;e+=4)po[0]=c[e+0],po[1]=c[e+1],po[2]=c[e+2],p.transformPoint4(n,po,Ao),i?(p.transformPoint4(i,Ao,fo),p.expandAABB3Point3(a,fo)):p.expandAABB3Point3(a,Ao);if(this._state.origin){const e=this._state.origin;a[0]+=e[0],a[1]+=e[1],a[2]+=e[2],a[3]+=e[0],a[4]+=e[1],a[5]+=e[2]}p.expandAABB3(this.aabb,a),this._state.numInstances++;const h=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,h}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,s=t/4;if(t>0){let t=!1;this._state.colorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";uo[0]=t[0],uo[1]=t[1],uo[2]=t[2],uo[3]=t[3],this._state.colorsBuf.setData(uo,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&M),i=!!(t&V),a=!!(t&j),r=!!(t&k),l=!!(t&Q),o=!!(t&H),c=!!(t&F);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,h=!n||c?or.NOT_RENDERED:r?or.SILHOUETTE_SELECTED:a?or.SILHOUETTE_HIGHLIGHTED:i?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let p=0;p=!n||c?or.NOT_RENDERED:r?or.EDGES_SELECTED:a?or.EDGES_HIGHLIGHTED:i?or.EDGES_XRAYED:l?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?or.PICK:or.NOT_RENDERED)<<12,A|=(t&U?255:0)<<16,ho[0]=A,this._state.flagsBuf.setData(ho,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Io[0]=t[0],Io[1]=t[1],Io[2]=t[2],this._state.offsetsBuf.setData(Io,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class mo extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,n=[];return n.push("#version 300 es"),n.push("// Points batching color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&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("// Points batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class vo extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform vec4 color;"),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points batching silhouette vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("uniform vec4 color;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = color;"),a.push("}"),a}}class wo extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),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("// Points batching pick mesh vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class go extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batched pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),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("// Points batched 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("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("in float vFlags;");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 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 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class To extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push(" gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points batching occlusion 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Eo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new mo(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new vo(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wo(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new go(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new To(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const bo={};class Do{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const Po=p.vec4(),Ro=p.vec4(),Co=p.vec4([0,0,0,1]),_o=p.vec4([0,0,0,1]),Bo=p.vec4([0,0,0,1]),Oo=p.OBB3();class So{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=bo[t];return s||(s=new Eo(e),bo[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete bo[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Do(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new We({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:p.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=p.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.color,i=e.colorsCompressed,a=e.colors,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB,c=e.pickColor,u=this._buffer,h=u.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e<t;e++)u.positions.push(s[e]);const e=bt.getPositionsBounds(s),t=bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,Po),n=bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,Ro);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(p.AABB3ToOBB3(o,Oo),p.transformOBB3(l,Oo),p.OBB3ToAABB3(Oo,o)),A=s.length/3}else{if(!t)throw"positions expected";A=t.length/3;const e=t.length,s=u.positions.length;for(let e=0,s=t.length;e<s;e++)u.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)Co[0]=u.positions[t+0],Co[1]=u.positions[t+1],Co[2]=u.positions[t+2],p.transformPoint4(r,Co,_o),u.positions[t+0]=_o[0],u.positions[t+1]=_o[1],u.positions[t+2]=_o[2],p.expandAABB3Point3(this._modelAABB,_o),l?(p.transformPoint4(l,_o,Bo),p.expandAABB3Point3(o,Bo)):p.expandAABB3Point3(o,_o);else for(let t=s,n=s+e;t<n;t+=3)Co[0]=u.positions[t+0],Co[1]=u.positions[t+1],Co[2]=u.positions[t+2],p.expandAABB3Point3(this._modelAABB,Co),l?(p.transformPoint4(l,Co,_o),p.expandAABB3Point3(o,_o)):p.expandAABB3Point3(o,Co)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(p.expandAABB3(this.aabb,o),i)for(let e=0,t=i.length;e<t;e++)u.colors.push(i[e]);else if(a)for(let e=0,t=a.length;e<t;e++)u.colors.push(255*a[e]);else if(n){const e=n[0],t=n[1],s=n[2],i=1;for(let n=0;n<A;n++)u.colors.push(e),u.colors.push(t),u.colors.push(s),u.colors.push(i)}{const e=u.pickColors.length;for(let t=e,s=e+4*A;t<s;t+=4)u.pickColors.push(c[0]),u.pickColors.push(c[1]),u.pickColors.push(c[2]),u.pickColors.push(c[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)u.offsets.push(0),u.offsets.push(0),u.offsets.push(0);const d=this._portions.length/2;return this._portions.push(h),this._portions.push(A),this._numPortions++,this.model.numPortions++,d}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=jr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n);let a=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=2*e,i=this._portions[n],a=this._portions[n+1],r=this._scratchMemory.getFloat32Array(a),l=!!(t&M),o=!!(t&V),c=!!(t&j),u=!!(t&k),h=!!(t&H),p=!!(t&F);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,d=!l||p?or.NOT_RENDERED:u?or.SILHOUETTE_SELECTED:c?or.SILHOUETTE_HIGHLIGHTED:o?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let f=l&&!p&&h?or.PICK:or.NOT_RENDERED;const I=t&U?1:0;for(let e=0;e<a;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,r[e]=t}this._state.flagsBuf.setData(r,i)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class No extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&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("// Points instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class xo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 color;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),n.push("uniform vec4 silhouetteColor;"),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Lo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class Mo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push(" vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing 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("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("in float vFlags;");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 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 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Fo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 color;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing occlusion vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Ho extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points instancing depth vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("const float packUpScale = 256. / 255.;"),a.push("const float unpackDownscale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),a.push("const float shiftRight8 = 1.0 / 256.;"),a.push("vec4 packDepthToRGBA( const in float v ) {"),a.push(" vec4 r = vec4( fract( v * packFactors ), v );"),a.push(" r.yzw -= r.xyz * shiftRight8;"),a.push(" return r * packUpScale;"),a.push("}"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return a.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Uo extends vr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Go{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new No(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ho(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Lo(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Mo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Fo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Uo(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Vo={};const jo=new Uint8Array(4),ko=new Float32Array(1),Qo=p.vec4([0,0,0,1]),Wo=p.vec4([0,0,0,1]),zo=p.vec4([0,0,0,1]),Ko=new Float32Array(3);class Yo{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=Vo[t];return s||(s=new Go(e),Vo[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Vo[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new We({obb:p.OBB3(),numInstances:0,origin:e.origin?p.vec3(e.origin):null,geometry:e.geometry,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.worldMatrix,n=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),p.collapseAABB3(n);const a=this._state.obb,r=a.length;for(let e=0;e<r;e+=4)Qo[0]=a[e+0],Qo[1]=a[e+1],Qo[2]=a[e+2],p.transformPoint4(t,Qo,Wo),s?(p.transformPoint4(s,Wo,zo),p.expandAABB3Point3(n,zo)):p.expandAABB3Point3(n,Wo);if(this._state.origin){const e=this._state.origin;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}p.expandAABB3(this.aabb,n),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4;if(t>0){let s=!1;this._state.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;this._state.pickColorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";jo[0]=t[0],jo[1]=t[1],jo[2]=t[2],this._state.colorsBuf.setData(jo,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&M),i=!!(t&V),a=!!(t&j),r=!!(t&k),l=!!(t&Q),o=!!(t&H),c=!!(t&F);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,h=!n||c?or.NOT_RENDERED:r?or.SILHOUETTE_SELECTED:a?or.SILHOUETTE_HIGHLIGHTED:i?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let p=0;p=!n||c?or.NOT_RENDERED:r?or.EDGES_SELECTED:a?or.EDGES_HIGHLIGHTED:i?or.EDGES_XRAYED:l?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?or.PICK:or.NOT_RENDERED)<<12,A|=(t&U?255:0)<<16,ko[0]=A,this._state.flagsBuf.setData(ko,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ko[0]=t[0],Ko[1]=t[1],Ko[2]=t[2],this._state.offsetsBuf.setData(Ko,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class Xo{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class qo{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Jo={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Zo{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t<s;t+=2){const s=this.handlers[t],n=this.handlers[t+1];if(s.global&&(s.lastIndex=0),s.test(e))return n}return null}}const $o=new Zo;class ec{constructor(e){this.manager=void 0!==e?e:$o,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const s=this;return new Promise((function(n,i){s.load(e,n,t,i)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const tc={};class sc extends ec{constructor(e){super(e)}load(e,t,s,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=Jo.get(e);if(void 0!==i)return this.manager.itemStart(e),setTimeout((()=>{t&&t(i),this.manager.itemEnd(e)}),0),i;if(void 0!==tc[e])return void tc[e].push({onLoad:t,onProgress:s,onError:n});tc[e]=[],tc[e].push({onLoad:t,onProgress:s,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),r=this.mimeType,l=this.responseType;fetch(a).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const s=tc[e],n=t.body.getReader(),i=t.headers.get("Content-Length"),a=i?parseInt(i):0,r=0!==a;let l=0;const o=new ReadableStream({start(e){!function t(){n.read().then((({done:n,value:i})=>{if(n)e.close();else{l+=i.byteLength;const n=new ProgressEvent("progress",{lengthComputable:r,loaded:l,total:a});for(let e=0,t=s.length;e<t;e++){const t=s[e];t.onProgress&&t.onProgress(n)}e.enqueue(i),t()}}))}()}});return new Response(o)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r)));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),s=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(s);return e.arrayBuffer().then((e=>n.decode(e)))}}})).then((t=>{Jo.add(e,t);const s=tc[e];delete tc[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const s=tc[e];if(void 0===s)throw this.manager.itemError(e),t;delete tc[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onError&&n.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class nc{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:t,msg:s,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(s,n)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((s=>{const n=this._getIdleWorker();-1!==n?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=s,this.workers[n].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let ic=0;class ac{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new nc,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const n=e.capabilities;this._workerConfig={astcSupported:n.astcSupported,etc1Supported:n.etc1Supported,etc2Supported:n.etc2Supported,dxtSupported:n.dxtSupported,bptcSupported:n.bptcSupported,pvrtcSupported:n.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new sc;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new sc;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,n]).then((([e,t])=>{const s=ac.BasisWorker.toString(),n=["/* constants */","let _EngineFormat = "+JSON.stringify(ac.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(ac.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ac.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([n])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),ic>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),ic++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((n,i)=>{const a=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:a},e))).then((e=>{const s=e.data,{mipmaps:a,width:r,height:l,format:o,type:c,error:u,dfdTransferFn:h,dfdFlags:p}=s;if("error"===c)return i(u);t.setCompressedData({mipmaps:a,props:{format:o,minFilter:1===a.length?1006:1008,magFilter:1===a.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&p)}}),n()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),ic--}}ac.BasisFormat={ETC1S:0,UASTC_4x4:1},ac.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},ac.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},ac.BasisWorker=function(){let e,t,s;const n=_EngineFormat,i=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const u=r.data;switch(u.type){case"init":e=u.config,h=u.transcoderBinary,t=new Promise((e=>{s={wasmBinary:h,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f}=function(t){const r=new s.KTX2File(new Uint8Array(t));function u(){r.close(),r.delete()}if(!r.isValid())throw u(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=r.isUASTC()?a.UASTC_4x4:a.ETC1S,p=r.getWidth(),A=r.getHeight(),d=r.getLevels(),f=r.getHasAlpha(),I=r.getDFDTransferFunc(),y=r.getDFDFlags(),{transcoderFormat:m,engineFormat:v}=function(t,s,r,u){let h,p;const A=t===a.ETC1S?l:o;for(let n=0;n<A.length;n++){const i=A[n];if(e[i.if]&&(i.basisFormat.includes(t)&&!(u&&i.transcoderFormat.length<2)&&(!i.needsPowerOfTwo||c(s)&&c(r))))return h=i.transcoderFormat[u?1:0],p=i.engineFormat[u?1:0],{transcoderFormat:h,engineFormat:p}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=i.RGBA32,p=n.RGBAFormat,{transcoderFormat:h,engineFormat:p}}(h,p,A,f);if(!p||!A||!d)throw u(),new Error("KTX2TextureTranscoder: Invalid texture");if(!r.startTranscoding())throw u(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const w=[];for(let e=0;e<d;e++){const t=r.getImageLevelInfo(e,0,0),s=t.origWidth,n=t.origHeight,i=new Uint8Array(r.getImageTranscodedSizeInBytes(e,0,0,m));if(!r.transcodeImage(i,e,0,0,m,0,-1,-1))throw u(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");w.push({data:i,width:s,height:n})}return u(),{width:p,height:A,hasAlpha:f,mipmaps:w,format:v,dfdTransferFn:I,dfdFlags:y}}(u.buffers[0]),I=[];for(let e=0;e<p.length;++e)I.push(p[e].data.buffer);self.postMessage({type:"transcode",id:u.id,width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f},I)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:u.id,error:e.message})}}))}var h}));const r=[{if:"astcSupported",basisFormat:[a.UASTC_4x4],transcoderFormat:[i.ASTC_4x4,i.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC7_M5,i.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC1,i.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1,i.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.PVRTC1_4_RGB,i.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],l=r.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),o=r.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function c(e){return e<=2||0==(e&e-1)&&0!==e}};const rc={};function lc(e){const t=e.scene.id;let s=rc[t];return s||(s=new ac({viewer:e}),rc[t]=s,e.scene.on("destroyed",(()=>{delete rc[t],s.destroy()}))),s}
10
+ function is(e,t){t.length;const s=e.length,n=[],i=[],a=e=>{for(let s=0,n=e.meshIds.length;s<n;s++)if(t[e.meshIds[s]].geometryId)return!0;return!1};for(let r=0;r<s;r++){const s=e[r];if(a(s)){i.push(r);continue}const l=p.collapseAABB3();let o=0;s.meshIds.forEach((e=>{const s=t[e];let n,i;if(s.positionsCompressed){const e=bt.getPositionsBounds(s.positionsCompressed);n=bt.decompressPosition(e.min,s.positionsDecodeMatrix,[]),i=bt.decompressPosition(e.max,s.positionsDecodeMatrix,[])}else{const e=bt.getPositionsBounds(s.positions);n=e.min,i=e.max}n[0]+=s.origin[0],n[1]+=s.origin[1],n[2]+=s.origin[2],i[0]+=s.origin[0],i[1]+=s.origin[1],i[2]+=s.origin[2],p.expandAABB3Point3(l,n),p.expandAABB3Point3(l,i),o+=s.numPrimitives})),n[r]={aabb:l,numPrimitives:o,entityId:s.id}}let r,l=[],o={};if(Object.keys(n).length>0){r=function(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=e[s];n&&t.push({minX:n.aabb[0],minY:n.aabb[1],minZ:n.aabb[2],maxX:n.aabb[3],maxY:n.aabb[4],maxZ:n.aabb[5],entity:{id:s,xeokitId:n.entityId,meshes:[{numPrimitives:n.numPrimitives}]},numPrimitives:n.numPrimitives})}const s=new ss(4);return s.load(t),s}(n);let e=ns({aabbTree:r});l=e.orderedEntityIds,o=e.clusteringResult.entityIdToClusterIdMapping}return{orderedClusteredIndexes:l,entityIdToClusterIdMapping:o,instancedIndexes:i,rTreeBasedAabbTree:r}}const as=p.vec3(),rs=180/Math.PI,ls=new Float32Array(262144);for(let e=-256;e<256;e++)for(let t=-256;t<256;t++){const s=(e+256<<9)+(t+256),n=Math.max(Math.abs(e),Math.abs(t));ls[s]=Math.atan2(e/n,t/n)}function os(e,t){const s=256/Math.max(Math.abs(e),Math.abs(t)),n=Math.round(e*s)+255,i=Math.round(t*s)+255;return ls[(n<<9)+i]}class cs{constructor(){this._aabbTree=null,this._orderedMeshList=[],this._orderedEntityList=[],this._frustumProps={dirty:!0,wMultiply:1,hMultiply:1},this._cullFrame=0,this.finalized=!1}initializeVFCState(e,t){if(this.finalized)throw"Already finalized";const s=is(e,t);this._aabbTree=s.rTreeBasedAabbTree;for(let n=0,i=s.orderedClusteredIndexes.length;n<i;n++){const i=s.orderedClusteredIndexes[n],a=s.entityIdToClusterIdMapping[i],r=e[i],l=[];for(let e=0,s=r.meshIds.length;e<s;e++){const s=r.meshIds[e];t[s].id=this._orderedMeshList.length,l.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:a,mesh:t[s]})}r.meshIds=l,this._orderedEntityList.push(r)}for(let n=0,i=s.instancedIndexes.length;n<i;n++){let i=e[s.instancedIndexes[n]];const a=[];for(let e=0,s=i.meshIds.length;e<s;e++){const s=i.meshIds[e];t[s].id=this._orderedMeshList.length,a.push(this._orderedMeshList.length),this._orderedMeshList.push({clusterNumber:99999,mesh:t[s]})}i.meshIds=a,this._orderedEntityList.push(i)}}finalize(e,t){if(this.finalized)throw"Already finalized";let s=-1;for(let n=0,i=this._orderedMeshList.length;n<i;n++){const{clusterNumber:i,mesh:a}=this._orderedMeshList[n];-1!==s&&s!==i&&t.call(e),e._createMesh(a),s=i}for(let t=0,s=this._orderedEntityList.length;t<s;t++)e._createEntity(this._orderedEntityList[t]);this._orderedMeshList=[],this._orderedEntityList=[],this.finalized=!0}applyViewFrustumCulling(e){if(!this.finalized)throw"Not finalized";if(!this._aabbTree)return;this._canvasElement||(this._canvasElement=e.scene.canvas.canvas),this._camera||(this._camera=e.scene.camera),this._ensureFrustumPropsUpdated(e),this._initializeCullingDataIfNeeded(e);const t=this._searchVisibleNodesWithFrustumCulling();this._cullFrame++,this._markVisibleFrameOfVisibleNodes(t,this._cullFrame),this._cullNonVisibleNodes(e,this._cullFrame)}_initializeCullingDataIfNeeded(e){if(this._internalNodesList)return;if(!this._aabbTree)return;const t=this._aabbTree.all();let s=0;t.forEach((e=>{s=Math.max(s,e.entity.id)}));const n=new Array(s+1);t.forEach((t=>{n[t.entity.id]=e.objects[t.entity.xeokitId]})),this._internalNodesList=n,this._lastVisibleFrameOfNodes=new Array(n.length),this._lastVisibleFrameOfNodes.fill(0)}_searchVisibleNodesWithFrustumCulling(){return this._aabbTree.searchCustom(((e,t)=>this._aabbIntersectsCameraFrustum(e,t)),(e=>this._aabbContainedInCameraFrustum(e)))}_markVisibleFrameOfVisibleNodes(e,t){const s=this._lastVisibleFrameOfNodes;for(let n=0,i=e.length;n<i;n++)s[e[n].entity.id]=t}_cullNonVisibleNodes(e,t){const s=this._internalNodesList,n=this._lastVisibleFrameOfNodes;for(let e=0,i=s.length;e<i;e++)s[e]&&(s[e].culledVFC=n[e]!==t)}_getPointsForBBox(e){const t=[];for(let s=0;s<8;s++)t.push(new Float32Array([1&s?e.maxX:e.minX,2&s?e.maxY:e.minY,4&s?e.maxZ:e.minZ]));return t}_aabbIntersectsCameraFrustum(e,t){if(t)return!0;if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const s=this._aabbIntersectsCameraFrustum_internal(e);return!!((4096&s||!(1&s||2&s)||1&s)&&(8192&s||!(16&s||32&s)||16&s)&&(16384&s||!(256&s||512&s)||256&s))}_aabbContainedInCameraFrustum(e){if("ortho"===this._camera.projection)return this._frustumProps.dirty=!1,!0;const t=e._check;return 1&t&&16&t&&256&t}_ensureFrustumPropsUpdated(e){const t=Math.min(this._canvasElement.width,this._canvasElement.height);this._frustumProps.wMultiply=this._canvasElement.width/t,this._frustumProps.hMultiply=this._canvasElement.height/t;const s=this._canvasElement.width/this._canvasElement.height;let n=this._camera.perspective.fov;s<1&&(n/=s),n=Math.min(n,120),this._frustumProps.fov=n;const i=p.inverseMat4(e.worldMatrix,p.mat4()),a=p.transformVec3(i,this._camera.eye,[0,0,0]),r=p.transformVec3(i,this._camera.look,[0,0,0]);this._frustumProps.forward=p.normalizeVec3(p.subVec3(r,a,[0,0,0]),[0,0,0]),this._frustumProps.up=p.normalizeVec3(this._camera.up,[0,0,0]),this._frustumProps.right=p.normalizeVec3(p.cross3Vec3(this._frustumProps.forward,this._frustumProps.up,[0,0,0]),[0,0,0]),this._frustumProps.eye=a.slice(),this._frustumProps.CAM_FACTOR_1=this._frustumProps.fov/2*this._frustumProps.wMultiply/rs,this._frustumProps.CAM_FACTOR_2=this._frustumProps.fov/2*this._frustumProps.hMultiply/rs}_aabbIntersectsCameraFrustum_internal(e){const t=e._points||this._getPointsForBBox(e);e._points=t;let s=819;for(let e=0,n=t.length;e<n;e++){const n=t[e],i=as;i[0]=n[0]-this._frustumProps.eye[0],i[1]=n[1]-this._frustumProps.eye[1],i[2]=n[2]-this._frustumProps.eye[2];const a=p.dotVec3(i,this._frustumProps.forward);a<0?(s|=4,s&=-2):(s|=8,s&=-3);const r=os(p.dotVec3(i,this._frustumProps.right),a);Math.abs(r)>this._frustumProps.CAM_FACTOR_1?(s|=r<0?64:128,s&=-17):s&=-33;const l=os(p.dotVec3(i,this._frustumProps.up),a);Math.abs(l)>this._frustumProps.CAM_FACTOR_2?(s|=l<0?1024:2048,s&=-257):s&=-513}return 4&s&&8&s&&(s|=4096),64&s&&128&s&&(s|=8192),1024&s&&2048&s&&(s|=16384),e._check=s,s}}class us{constructor(e,t){this.sceneModel=t,this.entities=[],this.meshes=[],this.finalized=!1}addEntity(e){if(this.finalized)throw"Already finalized";this.entities.push(e)}addMesh(e){if(this.finalized)throw"Already finalized";this.meshes.push(e)}finalize(e){if(this.finalized)throw"Already finalized";this.finalized=!0,this.VFCState=new cs,this.VFCState.initializeVFCState(this.entities,this.meshes),this.VFCState.finalize(this.sceneModel,e),this._onSceneRendering=this.sceneModel.scene.on("rendering",(()=>this.applyViewFrustumCulling.call(this)))}applyViewFrustumCulling(){this.finalized&&this.VFCState.applyViewFrustumCulling(this.sceneModel)}destroy(){this.finalized&&this.sceneModel.off(this._onSceneRendering)}}class hs extends _{constructor(e,t={}){super(e,t),this._scene=e,this._vfcManagers={},this._vfcManagerList=[],this.enabled=t.enabled,this._init()}_init(){this._scene.on("rendering",(()=>{for(let e=0,t=this._vfcManagerList.length;e<t;e++)this._vfcManagerList[e].applyViewFrustumCulling()}))}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}getVFCManager(e){const t=new us(this.scene,e);return this._vfcManagers[t.id]=t,this._vfcManagerList=Object.values(this._vfcManagers),t}putVFCManager(e){delete this._vfcManagers[e.id],this._vfcManagerList=Object.values(this._vfcManagers)}destroy(){super.destroy()}}function ps(e,t){const s={};let n,i;for(let a=0,r=t.length;a<r;a++)n=t[a],i=e.component[n],i?i.isEntity?s[n]=!0:e.warn("pick(): Component is not an Entity: "+n):e.warn("pick(): Component not found: "+n);return s}class As extends _{get type(){return"Scene"}constructor(e,t={}){super(null,t);const s=t.canvasElement||document.getElementById(t.canvasId);if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";const n=!!t.transparent,i=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new fe(this,{dontClear:!0,canvas:s,spinnerElementId:t.spinnerElementId,transparent:n,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new je(this,{transparent:n,alphaDepthMask:i}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,n=t.length;e<n;e++)s.push("cp");return s.push(";"),e=s.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let s=0,n=this.sectionPlanes.length;s<n;s++)if(this.sectionPlanes[s].id===t.id)return this.sectionPlanes.splice(s,1),void(e=null)}},this._lightsState=new function(){const e=p.vec4([0,0,0,0]),t=p.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,n=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let n;for(let s=0,i=t.length;s<i;s++)n=t[s],e.push("/"),e.push(n.type),e.push("world"===n.space?"w":"v"),n.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),n=null,s=null},this.removeLight=function(e){for(let t=0,i=this.lights.length;t<i;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),n&&n.id===e.id&&(n=null),void(s=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),s=null},this.removeReflectionMap=function(e){for(let t=0,n=this.reflectionMaps.length;t<n;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(s=null)},this.addLightMap=function(e){this.lightMaps.push(e),s=null},this.removeLightMap=function(e){for(let t=0,n=this.lightMaps.length;t<n;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(s=null)},this.getAmbientColorAndIntensity=function(){if(!n)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){n=t;break}}if(n){const e=n.color,s=n.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=s,t}return e}},this.input=new ke(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new Ht(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Ut(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,R._addScene(this),this._initDefaults(),this._viewport=new ze(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new pt(this,{id:"default.camera",dontClear:!0}),new ft(this,{color:[1,1,1],intensity:.7}),new dt(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new dt(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()})),this.lod=new $t(this,{enabled:t.lodEnabled}),this.vfc=new hs(this,{enabled:t.vfcEnabled})}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+m.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=p.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const n=this.types[s];n&&(delete n[t],m.isEmptyObject(n)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&R.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,n=this._clearEachPass;let i,a;for(i=0;i<s;i++)t.pass=i,this.fire("rendering",t,!0),a=n||0===i,this._renderer.render({pass:i,clear:a,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=p.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||Ct(Rt)}get material(){return this.components["default.material"]||new St(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new xt(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new xt(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new xt(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new Mt(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Vt(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new kt(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=p.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=p.AABB3());let e,t=p.MAX_DOUBLE,s=p.MAX_DOUBLE,n=p.MAX_DOUBLE,i=p.MIN_DOUBLE,a=p.MIN_DOUBLE,r=p.MIN_DOUBLE;const l=this._collidables;let o,c=!1;for(const u in l)if(l.hasOwnProperty(u)){if(o=l[u],!1===o.collidable)continue;e=o.aabb,e[0]<t&&(t=e[0]),e[1]<s&&(s=e[1]),e[2]<n&&(n=e[2]),e[3]>i&&(i=e[3]),e[4]>a&&(a=e[4]),e[5]>r&&(r=e[5]),c=!0}c||(t=-100,s=-100,n=-100,i=100,a=100,r=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=n,this._aabb[3]=i,this._aabb[4]=a,this._aabb[5]=r,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const s=e.includeEntities||e.include;s&&(e.includeEntityIds=ps(this,s));const n=e.excludeEntities||e.exclude;return n&&(e.excludeEntityIds=ps(this,n)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}snapPick(e){return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapMode||"vertex")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t<s;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,s=e.length;t<s;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,s=e.length;t<s;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,s=e.length;t<s;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(m.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,s=p.MAX_DOUBLE,n=p.MAX_DOUBLE,i=p.MAX_DOUBLE,a=p.MIN_DOUBLE,r=p.MIN_DOUBLE,l=p.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const o=e.aabb;o[0]<s&&(s=o[0]),o[1]<n&&(n=o[1]),o[2]<i&&(i=o[2]),o[3]>a&&(a=o[3]),o[4]>r&&(r=o[4]),o[5]>l&&(l=o[5]),t=!0}})),t){const e=p.AABB3();return e[0]=s,e[1]=n,e[2]=i,e[3]=a,e[4]=r,e[5]=l,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){m.isString(e)&&(e=[e]);let s=!1;for(let n=0,i=e.length;n<i;n++){const i=e[n];let a=this.objects[i];if(a)s=t(a)||s;else{const e=this.modelIds;for(let n=0,r=e.length;n<r;n++){const r=e[n],l=p.globalizeObjectId(r,i);a=this.objects[l],a&&(s=t(a)||s)}}}return s}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ds=1e3,fs=1001,Is=1002,ys=1003,ms=1004,vs=1004,ws=1005,gs=1005,Ts=1006,Es=1007,bs=1007,Ds=1008,Ps=1008,Rs=1009,Cs=1010,_s=1011,Bs=1012,Os=1013,Ss=1014,Ns=1015,xs=1016,Ls=1017,Ms=1018,Fs=1020,Hs=1021,Us=1022,Gs=1023,Vs=1024,js=1025,ks=1026,Qs=1027,Ws=1028,zs=1029,Ks=1030,Ys=1031,Xs=1033,qs=33776,Js=33777,Zs=33778,$s=33779,en=35840,tn=35841,sn=35842,nn=35843,an=36196,rn=37492,ln=37496,on=37808,cn=37809,un=37810,hn=37811,pn=37812,An=37813,dn=37814,fn=37815,In=37816,yn=37817,mn=37818,vn=37819,wn=37820,gn=37821,Tn=36492,En=3e3,bn=3001,Dn=1e4,Pn=10001,Rn=10002,Cn=10003,_n=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene._lightsState,i=e._geometry._state,a=e._state.billboard,r=e._state.stationary,l=s.sectionPlanes.length>0,o=!!i.compressGeometry,c=[];c.push("#version 300 es"),c.push("// Lambertian drawing vertex shader"),c.push("in vec3 position;"),c.push("uniform mat4 modelMatrix;"),c.push("uniform mat4 viewMatrix;"),c.push("uniform mat4 projMatrix;"),c.push("uniform vec4 colorize;"),c.push("uniform vec3 offset;"),o&&c.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(c.push("uniform float logDepthBufFC;"),c.push("out float vFragDepth;"),c.push("bool isPerspectiveMatrix(mat4 m) {"),c.push(" return (m[2][3] == - 1.0);"),c.push("}"),c.push("out float isPerspective;"));l&&c.push("out vec4 vWorldPosition;");if(c.push("uniform vec4 lightAmbient;"),c.push("uniform vec4 materialColor;"),c.push("uniform vec3 materialEmissive;"),i.normalsBuf){c.push("in vec3 normal;"),c.push("uniform mat4 modelNormalMatrix;"),c.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(c.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&c.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&c.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(c.push("uniform vec3 lightPos"+e+";"),c.push("uniform vec3 lightDir"+e+";")))}o&&(c.push("vec3 octDecode(vec2 oct) {"),c.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),c.push(" if (v.z < 0.0) {"),c.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);"),c.push(" }"),c.push(" return normalize(v);"),c.push("}"))}c.push("out vec4 vColor;"),"points"===i.primitiveName&&c.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(c.push("void billboard(inout mat4 mat) {"),c.push(" mat[0][0] = 1.0;"),c.push(" mat[0][1] = 0.0;"),c.push(" mat[0][2] = 0.0;"),"spherical"===a&&(c.push(" mat[1][0] = 0.0;"),c.push(" mat[1][1] = 1.0;"),c.push(" mat[1][2] = 0.0;")),c.push(" mat[2][0] = 0.0;"),c.push(" mat[2][1] = 0.0;"),c.push(" mat[2][2] =1.0;"),c.push("}"));c.push("void main(void) {"),c.push("vec4 localPosition = vec4(position, 1.0); "),c.push("vec4 worldPosition;"),o&&c.push("localPosition = positionsDecodeMatrix * localPosition;");i.normalsBuf&&(o?c.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):c.push("vec4 localNormal = vec4(normal, 0.0); "),c.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),c.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));c.push("mat4 viewMatrix2 = viewMatrix;"),c.push("mat4 modelMatrix2 = modelMatrix;"),r&&c.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===a||"cylindrical"===a?(c.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),c.push("billboard(modelMatrix2);"),c.push("billboard(viewMatrix2);"),c.push("billboard(modelViewMatrix);"),i.normalsBuf&&(c.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),c.push("billboard(modelNormalMatrix2);"),c.push("billboard(viewNormalMatrix2);"),c.push("billboard(modelViewNormalMatrix);")),c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i.normalsBuf&&c.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(c.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),c.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),c.push("float lambertian = 1.0;"),i.normalsBuf)for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?c.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):c.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}c.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),c.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}c.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),l&&c.push("vWorldPosition = worldPosition;");"points"===i.primitiveName&&c.push("gl_PointSize = pointSize;");c.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(c.push("vFragDepth = 1.0 + clipPos.w;"),c.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return c.push("gl_Position = clipPos;"),c.push("}"),c}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState;e._material._state;const n=e._geometry._state,i=s.sectionPlanes.length>0,a=t.gammaOutput,r=[];r.push("#version 300 es"),r.push("// Lambertian drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(i){r.push("in vec4 vWorldPosition;"),r.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}r.push("in vec4 vColor;"),a&&(r.push("uniform float gammaFactor;"),r.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}"));if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}"points"===n.primitiveName&&(r.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push("float r = dot(cxy, cxy);"),r.push("if (r > 1.0) {"),r.push(" discard;"),r.push("}"));t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");a?r.push("outColor = linearToGamma(vColor, gammaFactor);"):r.push("outColor = vColor;");return r.push("}"),r}(e)):(this.vertex=function(e){const t=e.scene;e._material;const s=e._state,n=t._sectionPlanesState,i=e._geometry._state,a=t._lightsState;let r;const l=s.billboard,o=s.background,c=s.stationary,u=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=Sn(e),p=n.sectionPlanes.length>0,A=On(e),d=!!i.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),p&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));a.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===r.type&&"view"===r.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));d&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.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);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}u&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&f.push("uniform mat3 uvDecodeMatrix;"));i.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===i.primitiveName&&f.push("uniform float pointSize;");"spherical"!==l&&"cylindrical"!==l||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===l&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),d&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(d?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),c?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):o&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&"world"===r.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===r.type&&("world"===r.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}u&&(d?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));i.colors&&f.push("vColor = color;");"points"===i.primitiveName&&f.push("gl_PointSize = pointSize;");p&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));o&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=e._material,n=e._geometry._state,i=e.scene._sectionPlanesState,a=e.scene._lightsState,r=e._material._state,l=i.sectionPlanes.length>0,o=Sn(e),c=n.uvBuf,u="PhongMaterial"===r.type,h="MetallicMaterial"===r.type,p="SpecularMaterial"===r.type,A=On(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));A&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(l){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var I=0;I<i.sectionPlanes.length;I++)f.push("uniform bool sectionPlaneActive"+I+";"),f.push("uniform vec3 sectionPlanePos"+I+";"),f.push("uniform vec3 sectionPlaneDir"+I+";")}o&&(a.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),u&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Bn[a.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||p)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),a.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Bn[a.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),n.colors&&f.push("in vec4 vColor;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");o&&(a.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));r.ambient&&f.push("uniform vec3 materialAmbient;");r.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==r.alpha&&null!==r.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");r.emissive&&f.push("uniform vec3 materialEmissive;");r.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==r.glossiness&&null!==r.glossiness&&f.push("uniform float materialGlossiness;");void 0!==r.shininess&&null!==r.shininess&&f.push("uniform float materialShininess;");r.specular&&f.push("uniform vec3 materialSpecular;");void 0!==r.metallic&&null!==r.metallic&&f.push("uniform float materialMetallic;");void 0!==r.roughness&&null!==r.roughness&&f.push("uniform float materialRoughness;");void 0!==r.specularF0&&null!==r.specularF0&&f.push("uniform float materialSpecularF0;");c&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));c&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));c&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));c&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));o&&c&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));o&&c&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));o&&c&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));o&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));c&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));c&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));o&&c&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));o&&c&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));o&&c&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));o&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),o)for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(A)for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),l){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(I=0;I<i.sectionPlanes.length;I++)f.push("if (sectionPlaneActive"+I+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+I+".xyz, vWorldPosition.xyz - sectionPlanePos"+I+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===n.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),r.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");r.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):r.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");n.colors&&f.push("diffuseColor *= vColor.rgb;");r.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");r.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==r.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");n.colors&&f.push("alpha *= vColor.a;");void 0!==r.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==r.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==r.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==r.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));c&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Bn[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));c&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Bn[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));c&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Bn[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));c&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Bn[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));c&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));c&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(o&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){c&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),u&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),p&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),u&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||h)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),A&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),u&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}u?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),d&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},Bn={};function On(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,s=t.length;e<s;e++)if(t[e].castsShadow)return!0;return!1}function Sn(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}Bn[3e3]="linearToLinear",Bn[3001]="sRGBToLinear";const Nn=p.vec3(),xn=new e({}),Ln=function(e,t){this.id=xn.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new _n(t),this._allocate(t)},Mn={};Ln.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let n=Mn[s];if(!n){if(n=new Ln(s,e),n.errors)return console.log(n.errors.join("\n")),null;Mn[s]=n,d.memory.programs++}return n._useCount++,n},Ln.prototype.put=function(){0==--this._useCount&&(xn.removeItem(this.id),this._program&&this._program.destroy(),delete Mn[this._hash],d.memory.programs--)},Ln.prototype.webglContextRestored=function(){this._program=null},Ln.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=pe.MAX_TEXTURE_UNITS,n=t.scene,i=t._material,a=n.canvas.gl,r=this._program,l=t._state,o=t._material._state,c=t._geometry._state,u=n.camera,h=t.origin,p=l.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,p&&a.depthFunc(a.LEQUAL),this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(l.originHash,h):u.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,u.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,h?L(n.dist,n.dir,h,Nn):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(o.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=o.backfaces;e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t);const n=o.frontface;switch(e.frontface!==n&&(n?a.frontFace(a.CCW):a.frontFace(a.CW),e.frontface=n),e.lineWidth!==o.lineWidth&&(a.lineWidth(o.lineWidth),e.lineWidth=o.lineWidth),this._uPointSize&&a.uniform1f(this._uPointSize,o.pointSize),o.type){case"LambertMaterial":this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialColor&&a.uniform4f(this._uMaterialColor,o.color[0],o.color[1],o.color[2],o.alpha),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive);break;case"PhongMaterial":this._uMaterialShininess&&a.uniform1f(this._uMaterialShininess,o.shininess),this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0),i._ambientMap&&i._ambientMap._state.texture&&this._uMaterialAmbientMap&&(r.bindTexture(this._uMaterialAmbientMap,i._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMaterialAmbientMapMatrix&&a.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,i._ambientMap._state.matrix)),i._diffuseMap&&i._diffuseMap._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,i._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,i._diffuseMap._state.matrix)),i._specularMap&&i._specularMap._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,i._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,i._specularMap._state.matrix)),i._emissiveMap&&i._emissiveMap._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,i._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,i._emissiveMap._state.matrix)),i._alphaMap&&i._alphaMap._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,i._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,i._alphaMap._state.matrix)),i._reflectivityMap&&i._reflectivityMap._state.texture&&this._uReflectivityMap&&(r.bindTexture(this._uReflectivityMap,i._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,this._uReflectivityMapMatrix&&a.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,i._reflectivityMap._state.matrix)),i._normalMap&&i._normalMap._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,i._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,i._normalMap._state.matrix)),i._occlusionMap&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,i._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,i._occlusionMap._state.matrix)),i._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&a.uniform1f(this._uDiffuseFresnelEdgeBias,i._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&a.uniform1f(this._uDiffuseFresnelCenterBias,i._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&a.uniform3fv(this._uDiffuseFresnelEdgeColor,i._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&a.uniform3fv(this._uDiffuseFresnelCenterColor,i._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&a.uniform1f(this._uDiffuseFresnelPower,i._diffuseFresnel.power)),i._specularFresnel&&(this._uSpecularFresnelEdgeBias&&a.uniform1f(this._uSpecularFresnelEdgeBias,i._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&a.uniform1f(this._uSpecularFresnelCenterBias,i._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&a.uniform3fv(this._uSpecularFresnelEdgeColor,i._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&a.uniform3fv(this._uSpecularFresnelCenterColor,i._specularFresnel.centerColor),this._uSpecularFresnelPower&&a.uniform1f(this._uSpecularFresnelPower,i._specularFresnel.power)),i._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&a.uniform1f(this._uAlphaFresnelEdgeBias,i._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&a.uniform1f(this._uAlphaFresnelCenterBias,i._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&a.uniform3fv(this._uAlphaFresnelEdgeColor,i._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&a.uniform3fv(this._uAlphaFresnelCenterColor,i._alphaFresnel.centerColor),this._uAlphaFresnelPower&&a.uniform1f(this._uAlphaFresnelPower,i._alphaFresnel.power)),i._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&a.uniform1f(this._uReflectivityFresnelEdgeBias,i._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&a.uniform1f(this._uReflectivityFresnelCenterBias,i._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&a.uniform3fv(this._uReflectivityFresnelEdgeColor,i._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&a.uniform3fv(this._uReflectivityFresnelCenterColor,i._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&a.uniform1f(this._uReflectivityFresnelPower,i._reflectivityFresnel.power)),i._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&a.uniform1f(this._uEmissiveFresnelEdgeBias,i._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&a.uniform1f(this._uEmissiveFresnelCenterBias,i._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&a.uniform3fv(this._uEmissiveFresnelEdgeColor,i._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&a.uniform3fv(this._uEmissiveFresnelCenterColor,i._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&a.uniform1f(this._uEmissiveFresnelPower,i._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&a.uniform3fv(this._uBaseColor,o.baseColor),this._uMaterialMetallic&&a.uniform1f(this._uMaterialMetallic,o.metallic),this._uMaterialRoughness&&a.uniform1f(this._uMaterialRoughness,o.roughness),this._uMaterialSpecularF0&&a.uniform1f(this._uMaterialSpecularF0,o.specularF0),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const t=i._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(r.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uBaseColorMapMatrix&&a.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const n=i._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(r.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicMapMatrix&&a.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const l=i._roughnessMap;l&&l._state.texture&&this._uRoughnessMap&&(r.bindTexture(this._uRoughnessMap,l._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uRoughnessMapMatrix&&a.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,l._state.matrix));const c=i._metallicRoughnessMap;c&&c._state.texture&&this._uMetallicRoughnessMap&&(r.bindTexture(this._uMetallicRoughnessMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&a.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,c._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialGlossiness&&a.uniform1f(this._uMaterialGlossiness,o.glossiness),this._uMaterialReflectivity&&a.uniform1f(this._uMaterialReflectivity,o.reflectivity),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const u=i._diffuseMap;u&&u._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,u._state.matrix));const h=i._specularMap;h&&h._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const p=i._glossinessMap;p&&p._state.texture&&this._uGlossinessMap&&(r.bindTexture(this._uGlossinessMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uGlossinessMapMatrix&&a.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,p._state.matrix));const y=i._specularGlossinessMap;var A,d,f,I;y&&y._state.texture&&this._uSpecularGlossinessMap&&(r.bindTexture(this._uSpecularGlossinessMap,y._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&a.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,y._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix))}this._lastMaterialId=o.id}if(a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),this._uColorize){const e=l.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(a.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}a.uniform3fv(this._uOffset,l.offset),c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(c.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(c.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(c.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(c.flagsBuf),e.bindArray++),c.indicesBuf&&(c.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=c.id),c.indicesBuf?(a.drawElements(c.primitive,c.indicesBuf.numItems,c.indicesBuf.itemType,0),e.drawElements++):c.positions&&(a.drawArrays(a.TRIANGLES,0,c.positions.numItems),e.drawArrays++),p&&a.depthFunc(a.LESS)},Ln.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=e._material,i=t._lightsState,a=t._sectionPlanesState,r=e._material._state;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const l=this._program;this._uPositionsDecodeMatrix=l.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=l.getLocation("uvDecodeMatrix"),this._uModelMatrix=l.getLocation("modelMatrix"),this._uModelNormalMatrix=l.getLocation("modelNormalMatrix"),this._uViewMatrix=l.getLocation("viewMatrix"),this._uViewNormalMatrix=l.getLocation("viewNormalMatrix"),this._uProjMatrix=l.getLocation("projMatrix"),this._uGammaFactor=l.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=l.getLocation("logDepthBufFC"));const o=i.lights;let c;for(var u=0,h=o.length;u<h;u++){switch(c=o[u],c.type){case"ambient":this._uLightAmbient[u]=l.getLocation("lightAmbient");break;case"dir":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=null,this._uLightDir[u]=l.getLocation("lightDir"+u);break;case"point":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=null,this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u);break;case"spot":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=l.getLocation("lightDir"+u),this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u)}c.castsShadow&&(this._uShadowViewMatrix[u]=l.getLocation("shadowViewMatrix"+u),this._uShadowProjMatrix[u]=l.getLocation("shadowProjMatrix"+u))}i.lightMaps.length>0&&(this._uLightMap="lightMap"),i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(u=0,h=a.sectionPlanes.length;u<h;u++)this._uSectionPlanes.push({active:l.getLocation("sectionPlaneActive"+u),pos:l.getLocation("sectionPlanePos"+u),dir:l.getLocation("sectionPlaneDir"+u)});switch(this._uPointSize=l.getLocation("pointSize"),r.type){case"LambertMaterial":this._uMaterialColor=l.getLocation("materialColor"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=l.getLocation("materialAmbient"),this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=l.getLocation("materialShininess"),n._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=l.getLocation("ambientMapMatrix")),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=l.getLocation("reflectivityMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=l.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=l.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=l.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=l.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=l.getLocation("diffuseFresnelPower")),n._specularFresnel&&(this._uSpecularFresnelEdgeBias=l.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=l.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=l.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=l.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=l.getLocation("specularFresnelPower")),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias=l.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=l.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=l.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=l.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=l.getLocation("alphaFresnelPower")),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=l.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=l.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=l.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=l.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=l.getLocation("reflectivityFresnelPower")),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=l.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=l.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=l.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=l.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=l.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=l.getLocation("materialBaseColor"),this._uMaterialMetallic=l.getLocation("materialMetallic"),this._uMaterialRoughness=l.getLocation("materialRoughness"),this._uMaterialSpecularF0=l.getLocation("materialSpecularF0"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=l.getLocation("baseColorMapMatrix")),n._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=l.getLocation("metallicMapMatrix")),n._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=l.getLocation("roughnessMapMatrix")),n._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=l.getLocation("metallicRoughnessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialGlossiness=l.getLocation("materialGlossiness"),this._uMaterialReflectivity=l.getLocation("reflectivityFresnel"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=l.getLocation("glossinessMapMatrix")),n._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=l.getLocation("materialSpecularGlossinessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"))}this._aPosition=l.getAttribute("position"),this._aNormal=l.getAttribute("normal"),this._aUV=l.getAttribute("uv"),this._aColor=l.getAttribute("color"),this._aFlags=l.getAttribute("flags"),this._uClippable=l.getLocation("clippable"),this._uColorize=l.getLocation("colorize"),this._uOffset=l.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},Ln.prototype._bindProgram=function(e){const t=pe.MAX_TEXTURE_UNITS,s=this._scene,n=s.canvas.gl,i=s._lightsState,a=s.camera.project;let r;const l=this._program;if(l.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}for(var o=0,c=i.lights.length;o<c;o++)if(r=i.lights[o],this._uLightAmbient[o])n.uniform4f(this._uLightAmbient[o],r.color[0],r.color[1],r.color[2],r.intensity);else if(this._uLightColor[o]&&n.uniform4f(this._uLightColor[o],r.color[0],r.color[1],r.color[2],r.intensity),this._uLightPos[o]&&(n.uniform3fv(this._uLightPos[o],r.pos),this._uLightAttenuation[o]&&n.uniform1f(this._uLightAttenuation[o],r.attenuation)),this._uLightDir[o]&&n.uniform3fv(this._uLightDir[o],r.dir),r.castsShadow){this._uShadowViewMatrix[o]&&n.uniformMatrix4fv(this._uShadowViewMatrix[o],!1,r.getShadowViewMatrix()),this._uShadowProjMatrix[o]&&n.uniformMatrix4fv(this._uShadowProjMatrix[o],!1,r.getShadowProjMatrix());const s=r.getShadowRenderBuf();s&&(l.bindTexture("shadowMap"+o,s.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}i.lightMaps.length>0&&i.lightMaps[0].texture&&this._uLightMap&&(l.bindTexture(this._uLightMap,i.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),i.reflectionMaps.length>0&&i.reflectionMaps[0].texture&&this._uReflectionMap&&(l.bindTexture(this._uReflectionMap,i.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class Fn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,n=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),i=t._sectionPlanesState.sectionPlanes.length>0,a=!!e._geometry._state.compressGeometry,r=e._state.billboard,l=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// EmphasisFillShaderSource vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 colorize;"),o.push("uniform vec3 offset;"),a&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");if(o.push("uniform vec4 lightAmbient;"),o.push("uniform vec4 fillColor;"),n){o.push("in vec3 normal;"),o.push("uniform mat4 modelNormalMatrix;"),o.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&o.push("uniform vec3 lightPos"+e+";"))}a&&(o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"))}o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),a&&o.push("localPosition = positionsDecodeMatrix * localPosition;");n&&(a?o.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):o.push("vec4 localNormal = vec4(normal, 0.0); "),o.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),o.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),l&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),n&&(o.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),o.push("billboard(modelNormalMatrix2);"),o.push("billboard(viewNormalMatrix2);"),o.push("billboard(modelViewNormalMatrix);")),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n&&o.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),n)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?o.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}o.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),i&&o.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&o.push("gl_PointSize = pointSize;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}"));t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const Hn=new e({}),Un=p.vec3(),Gn=function(e,t){this.id=Hn.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Fn(t),this._allocate(t)},Vn={};Gn.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Vn[t];return s||(s=new Gn(t,e),Vn[t]=s,d.memory.programs++),s._useCount++,s},Gn.prototype.put=function(){0==--this._useCount&&(Hn.removeItem(this.id),this._program&&this._program.destroy(),delete Vn[this._hash],d.memory.programs--)},Gn.prototype.webglContextRestored=function(){this._program=null},Gn.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl,r=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,l=t._state,o=t._geometry._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):i.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,c?L(n.dist,n.dir,c,Un):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(r.id!==this._lastMaterialId){const t=r.fillColor,s=r.backfaces;e.backfaces!==s&&(s?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=s),a.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(o.normalsBuf),e.bindArray++),o.indicesBuf?(o.indicesBuf.bind(),e.bindArray++):o.positionsBuf,this._lastGeometryId=o.id),o.indicesBuf?(a.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positionsBuf&&(a.drawArrays(a.TRIANGLES,0,o.positionsBuf.numItems),e.drawArrays++)},Gn.prototype._allocate=function(e){const t=e.scene,s=t._lightsState,n=t._sectionPlanesState,i=t.canvas.gl;if(this._program=new be(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=s.lights.length;e<t;e++){switch(s.lights[e].type){case"ambient":this._uLightAmbient[e]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=a.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=a.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=a.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+e),pos:a.getLocation("sectionPlanePos"+e),dir:a.getLocation("sectionPlaneDir"+e)});this._uFillColor=a.getLocation("fillColor"),this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._uClippable=a.getLocation("clippable"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uOffset=a.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Gn.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t._lightsState,i=t.camera,a=i.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];this._uLightAmbient[e]?s.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(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))}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor)};class jn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Edges drawing vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec4 edgeColor;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));s&&r.push("out vec4 vWorldPosition;");r.push("out vec4 vColor;"),("spherical"===i||"cylindrical"===i)&&(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.push("vColor = edgeColor;"),s&&r.push("vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const kn=new e({}),Qn=p.vec3(),Wn=function(e,t){this.id=kn.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new jn(t),this._allocate(t)},zn={};Wn.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=zn[t];return s||(s=new Wn(t,e),zn[t]=s,d.memory.programs++),s._useCount++,s},Wn.prototype.put=function(){0==--this._useCount&&(kn.removeItem(this.id),this._program&&this._program.destroy(),delete zn[this._hash],d.memory.programs--)},Wn.prototype.webglContextRestored=function(){this._program=null},Wn.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl;let r;const l=t._state,o=t._geometry,c=o._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(l.originHash,u):i.viewMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,u?L(n.dist,n.dir,u,Qn):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}switch(s){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;a.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let h;a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?h=o._getEdgeIndices():c.primitive===a.LINES&&(h=c.indicesBuf),h&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,h.numItems,h.itemType,0),e.drawElements++)},Wn.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=i.getLocation("edgeColor"),this._aPosition=i.getAttribute("position"),this._uClippable=i.getLocation("clippable"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uOffset=i.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Wn.prototype._bindProgram=function(e){const t=this._program,s=this._scene,n=s.canvas.gl,i=s.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor)};class Kn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh picking vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("out vec4 vViewPosition;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==i&&"cylindrical"!==i||(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"));r.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(i.push("uniform vec4 pickColor;"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = pickColor; "),i.push("}"),i}(e)}}const Yn=p.vec3(),Xn=function(e,t){this._hash=e,this._shaderSource=new Kn(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},qn={};Xn.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=qn[t];if(!s){if(s=new Xn(t,e),s.errors)return console.log(s.errors.join("\n")),null;qn[t]=s,d.memory.programs++}return s._useCount++,s},Xn.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete qn[this._hash],d.memory.programs--)},Xn.prototype.webglContextRestored=function(){this._program=null},Xn.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(i.originHash,l):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?L(s.dist,s.dir,l,Yn):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}if(a.id!==this._lastMaterialId){const t=a.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=a.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=a.id}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id);var o=t._state.pickID;const c=o>>24&255,u=o>>16&255,h=o>>8&255,p=255&o;n.uniform4f(this._uPickColor,p/255,h/255,u/255,c/255),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Xn.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uPickColor=n.getLocation("pickColor"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},Xn.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Jn{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry;e._state.billboard,e._state.stationary;const i=[];i.push("#version 300 es"),i.push("// Surface picking vertex shader"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform vec3 offset;"),s&&(i.push("uniform bool clippable;"),i.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"));i.push("out vec4 vColor;"),n&&i.push("uniform mat4 positionsDecodeMatrix;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),n&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push(" vec4 worldPosition = modelMatrix * localPosition; "),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&i.push(" vWorldPosition = worldPosition;");i.push(" vColor = color;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return i.push("gl_Position = clipPos;"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Surface picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = vColor;"),i.push("}"),i}(e)}}const Zn=p.vec3(),$n=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Jn(t),this._allocate(t)},ei={};$n.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=ei[t];if(!s){if(s=new $n(t,e),s.errors)return console.log(s.errors.join("\n")),null;ei[t]=s,d.memory.programs++}return s._useCount++,s},$n.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ei[this._hash],d.memory.programs--)},$n.prototype.webglContextRestored=function(){this._program=null},$n.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry,l=t._geometry._state,o=t.origin,c=a.backfaces,u=a.frontface,h=s.camera.project,p=r._getPickTrianglePositions(),A=r._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}if(n.uniformMatrix4fv(this._uViewMatrix,!1,o?e.getRTCPickViewMatrix(i.originHash,o):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,o?L(s.dist,s.dir,o,Zn):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.logarithmicDepthBufferEnabled&&n.uniform1f(this._uZFar,s.camera.project.far),e.backfaces!==c&&(c?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=c),e.frontface!==u&&(u?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=u),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(p,l.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT)):this._aPosition.bindArrayBuffer(p),A.bind(),n.enableVertexAttribArray(this._aColor.location),n.vertexAttribPointer(this._aColor.location,A.itemSize,A.itemType,!0,0,0),n.drawArrays(l.primitive,0,p.numItems/3)},$n.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._aColor=n.getAttribute("color"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))};class ti{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push("}"),i}(e)}}const si=p.vec3(),ni=function(e,t){this._hash=e,this._shaderSource=new ti(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},ii={};ni.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=ii[t];if(!s){if(s=new ni(t,e),s.errors)return console.log(s.errors.join("\n")),null;ii[t]=s,d.memory.programs++}return s._useCount++,s},ni.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete ii[this._hash],d.memory.programs--)},ni.prototype.webglContextRestored=function(){this._program=null},ni.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._material._state,a=t._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=i.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=i.id}const o=s.camera;if(n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCViewMatrix(a.originHash,l):o.viewMatrix),a.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?L(s.dist,s.dir,l,si):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),n.uniformMatrix4fv(this._uModelMatrix,n.FALSE,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},ni.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ni.prototype._bindProgram=function(e){const t=this._scene,s=t.camera.project,n=t.canvas.gl;if(this._program.bind(),e.useProgram++,n.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class ai{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,n=[];n.push("// Mesh shadow vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t&&n.push("out vec4 vWorldPosition;");n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("worldPosition = modelMatrix * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&n.push("vWorldPosition = worldPosition;");return n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("// Mesh shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("vec4 encodeFloat( const in float depth ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(depth * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return i.push("outColor = encodeFloat(gl_FragCoord.z);"),i.push("}"),i}(e)}}const ri=function(e,t){this._hash=e,this._shaderSource=new ai(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},li={};ri.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let n=li[s];if(!n){if(n=new ri(s,e),n.errors)return console.log(n.errors.join("\n")),null;li[s]=n,d.memory.programs++}return n._useCount++,n},ri.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete li[this._hash],d.memory.programs--)},ri.prototype.webglContextRestored=function(){this._program=null},ri.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,n=t._material._state,i=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){const t=n.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=n.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),e.lineWidth!==n.lineWidth&&(s.lineWidth(n.lineWidth),e.lineWidth=n.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,n.pointSize),this._lastMaterialId=n.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),i.combineGeometry){const n=t.vertexBufs;n.id!==this._lastVertexBufsId&&(n.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=n.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),i.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,i.positionsDecodeMatrix),i.combineGeometry?i.indicesBufCombined&&(i.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),i.indicesBuf&&(i.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=i.id),i.combineGeometry?i.indicesBufCombined&&(s.drawElements(i.primitive,i.indicesBufCombined.numItems,i.indicesBufCombined.itemType,0),e.drawElements++):i.indicesBuf?(s.drawElements(i.primitive,i.indicesBuf.numItems,i.indicesBuf.itemType,0),e.drawElements++):i.positions&&(s.drawArrays(s.TRIANGLES,0,i.positions.numItems),e.drawArrays++)},ri.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new be(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ri.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.sectionPlanes.length>0){let e,t,i,a,r;for(let l=0,o=this._uSectionPlanes.length;l<o;l++)e=this._uSectionPlanes[l],t=e.active,i=n.sectionPlanes[l],t&&s.uniform1i(t,i.active),a=e.pos,a&&s.uniform3fv(e.pos,i.pos),r=e.dir,r&&s.uniform3fv(e.dir,i.dir)}};class oi{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const ci=p.OBB3(),ui=p.vec4(),hi=p.vec4(),pi=p.vec4(),Ai=p.vec3([1,0,0]),di=p.vec3([0,1,0]),fi=p.vec3([0,0,1]),Ii=p.vec3(3),yi=p.vec3(3),mi=p.identityMat4();class vi extends _{constructor(e,t={}){super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new oi,this._state=new We({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:p.vec3(),origin:null,originHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=p.vec3(),this._quaternion=p.identityQuaternion(),this._rotation=p.vec3(),this._position=p.vec3(),this._worldMatrix=p.identityMat4(),this._worldNormalMatrix=p.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const s=t.origin||t.rtcCenter;if(s&&(this._state.origin=p.vec3(s),this._state.originHash=s.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),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.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),p.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=p.identityMat4()),p.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=p.identityMat4()),this.__localMatrix.set(e||mi),p.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=p.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const s=!!e;this.scene._objectColorizeUpdated(this,s),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const s=null!=e;t[3]=s?e:1,this.scene._objectOpacityUpdated(this,s),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Ln.get(this),this._emphasisFillRenderer=Gn.get(this),this._emphasisEdgesRenderer=Wn.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Xn.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=ni.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)p.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=p.mat4()),p.transposeMat4(this._worldMatrix,this._worldNormalMatrix),p.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=p.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),s.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){p.transformOBB3(e,this._geometry.obb,ci),p.OBB3ToAABB3(ci,t);const s=this._state.offset;if(t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[0],t[4]+=s[1],t[5]+=s[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return ui[0]=e[0],ui[1]=e[1],ui[2]=e[2],ui[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(ui,hi),p.mulQuaternions(this.quaternion,hi,pi),this.quaternion=pi,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return ui[0]=e[0],ui[1]=e[1],ui[2]=e[2],ui[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(ui,hi),p.mulQuaternions(hi,this.quaternion,hi),this}rotateX(e){return this.rotate(Ai,e)}rotateY(e){return this.rotate(di,e)}rotateZ(e){return this.rotate(fi,e)}translate(e,t){return p.vec3ApplyQuaternion(this.quaternion,e,Ii),p.mulVec3Scalar(Ii,t,yi),p.addVec3(this.position,yi,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ai,e)}translateY(e){return this.translate(di,e)}translateZ(e){return this.translate(fi,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s],n=this.renderFlags;if(t.active)if(this._state.origin){const e=p.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const i=0===e;n.sectionPlanesActivePerLayer[s]=i}else n.sectionPlanesActivePerLayer[s]=!0;else n.sectionPlanesActivePerLayer[s]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=Ln.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=Ln.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Gn.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Gn.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Gn.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Wn.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=ni.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=ri.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=Xn.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=$n.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,s){wi(this,e,t,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const wi=function(){const e=p.vec3(),t=p.vec3(),s=p.vec3(),n=p.vec3(),i=p.vec3(),a=p.vec3(),r=p.vec4(),l=p.vec3(),o=p.vec3(),c=p.vec3(),u=p.vec3(),h=p.vec3(),A=p.vec3(),d=p.vec3(),f=p.vec3(),I=p.vec3(),y=p.vec4(),m=p.vec4(),v=p.vec4(),w=p.vec3(),g=p.vec3(),T=p.vec3(),E=p.vec3(),b=p.vec3(),D=p.vec3(),P=p.vec3(),R=p.vec3(),C=p.vec3(),_=p.vec3(),B=p.vec3();return function(S,N,x,L){var M=L.primIndex;if(null!=M&&M>-1){const G=S.geometry._state,V=S.scene,j=V.camera,k=V.canvas;if("triangles"===G.primitiveName){L.primitive="triangle";const V=M,Q=G.indices,W=G.positions;let z,K,Y;if(Q){var F=Q[V+0],H=Q[V+1],U=Q[V+2];a[0]=F,a[1]=H,a[2]=U,L.indices=a,z=3*F,K=3*H,Y=3*U}else z=3*V,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],n[0]=W[K+0],n[1]=W[K+1],n[2]=W[K+2],i[0]=W[Y+0],i[1]=W[Y+1],i[2]=W[Y+2],G.compressGeometry){const e=G.positionsDecodeMatrix;e&&(bt.decompressPosition(s,e,s),bt.decompressPosition(n,e,n),bt.decompressPosition(i,e,i))}L.canvasPos?p.canvasPosToLocalRay(k.canvas,S.origin?O(N,S.origin):N,x,S.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&p.worldRayToLocalRay(S.worldMatrix,L.origin,L.direction,e,t),p.normalizeVec3(t),p.rayPlaneIntersect(e,t,s,n,i,r),L.localPos=r,L.position=r,y[0]=r[0],y[1]=r[1],y[2]=r[2],y[3]=1,p.transformVec4(S.worldMatrix,y,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],L.canvasPos&&S.origin&&(l[0]+=S.origin[0],l[1]+=S.origin[1],l[2]+=S.origin[2]),L.worldPos=l,p.transformVec4(j.matrix,m,v),o[0]=v[0],o[1]=v[1],o[2]=v[2],L.viewPos=o,p.cartesianToBarycentric(r,s,n,i,c),L.bary=c;const X=G.normals;if(X){if(G.compressGeometry){const e=3*F,t=3*H,s=3*U;bt.decompressNormal(X.subarray(e,e+2),u),bt.decompressNormal(X.subarray(t,t+2),h),bt.decompressNormal(X.subarray(s,s+2),A)}else u[0]=X[z],u[1]=X[z+1],u[2]=X[z+2],h[0]=X[K],h[1]=X[K+1],h[2]=X[K+2],A[0]=X[Y],A[1]=X[Y+1],A[2]=X[Y+2];const e=p.addVec3(p.addVec3(p.mulVec3Scalar(u,c[0],w),p.mulVec3Scalar(h,c[1],g),T),p.mulVec3Scalar(A,c[2],E),b);L.worldNormal=p.normalizeVec3(p.transformVec3(S.worldNormalMatrix,e,D))}const q=G.uv;if(q){if(d[0]=q[2*F],d[1]=q[2*F+1],f[0]=q[2*H],f[1]=q[2*H+1],I[0]=q[2*U],I[1]=q[2*U+1],G.compressGeometry){const e=G.uvDecodeMatrix;e&&(bt.decompressUV(d,e,d),bt.decompressUV(f,e,f),bt.decompressUV(I,e,I))}L.uv=p.addVec3(p.addVec3(p.mulVec2Scalar(d,c[0],P),p.mulVec2Scalar(f,c[1],R),C),p.mulVec2Scalar(I,c[2],_),B)}}}}}();function gi(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let n=e.height||1;n<0&&(console.error("negative height not allowed - will invert"),n*=-1);let i=e.radialSegments||32;i<0&&(console.error("negative radialSegments not allowed - will invert"),i*=-1),i<3&&(i=3);let a=e.heightSegments||1;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a<1&&(a=1);const r=!!e.openEnded;let l=e.center;const o=l?l[0]:0,c=l?l[1]:0,u=l?l[2]:0,h=n/2,p=n/a,A=2*Math.PI/i,d=1/i,f=(t-s)/a,I=[],y=[],v=[],w=[];let g,T,E,b,D,P,R,C,_,B,O;const S=(90-180*Math.atan(n/(s-t))/Math.PI)/90;for(g=0;g<=a;g++)for(D=t-g*f,P=h-g*p,T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),y.push(D*E),y.push(S),y.push(D*b),v.push(T*d),v.push(1*g/a),I.push(D*E+o),I.push(P+c),I.push(D*b+u);for(g=0;g<a;g++)for(T=0;T<=i;T++)R=g*(i+1)+T,C=R+i,w.push(R),w.push(C),w.push(C+1),w.push(R),w.push(C+1),w.push(R+1);if(!r&&t>0){for(_=I.length/3,y.push(0),y.push(1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,y.push(t*E),y.push(1),y.push(t*b),v.push(B),v.push(O),I.push(t*E+o),I.push(h+c),I.push(t*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(R),w.push(R+1),w.push(l)}if(!r&&s>0){for(_=I.length/3,y.push(0),y.push(-1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(0-h+c),I.push(0+u),T=0;T<=i;T++)E=Math.sin(T*A),b=Math.cos(T*A),B=.5*Math.sin(T*A)+.5,O=.5*Math.cos(T*A)+.5,y.push(s*E),y.push(-1),y.push(s*b),v.push(B),v.push(O),I.push(s*E+o),I.push(0-h+c),I.push(s*b+u);for(T=0;T<i;T++)l=_,R=_+1+T,w.push(l),w.push(R+1),w.push(R)}return m.apply(e,{positions:I,normals:y,uv:v,indices:w})}function Ti(e={}){const t=e.lod||1,s=e.center?e.center[0]:0,n=e.center?e.center[1]:0,i=e.center?e.center[2]:0;let a=e.radius||1;a<0&&(console.error("negative radius not allowed - will invert"),a*=-1);let r=e.heightSegments||18;r<0&&(console.error("negative heightSegments not allowed - will invert"),r*=-1),r=Math.floor(t*r),r<18&&(r=18);let l=e.widthSegments||18;l<0&&(console.error("negative widthSegments not allowed - will invert"),l*=-1),l=Math.floor(t*l),l<18&&(l=18);const o=[],c=[],u=[],h=[];let p,A,d,f,I,y,v,w,g,T,E,b,D,P,R;for(p=0;p<=r;p++)for(d=p*Math.PI/r,f=Math.sin(d),I=Math.cos(d),A=0;A<=l;A++)y=2*A*Math.PI/l,v=Math.sin(y),w=Math.cos(y),g=w*f,T=I,E=v*f,b=1-A/l,D=p/r,c.push(g),c.push(T),c.push(E),u.push(b),u.push(D),o.push(s+a*g),o.push(n+a*T),o.push(i+a*E);for(p=0;p<r;p++)for(A=0;A<l;A++)P=p*(l+1)+A,R=P+l+1,h.push(P+1),h.push(R+1),h.push(R),h.push(P+1),h.push(R),h.push(P);return m.apply(e,{positions:o,normals:c,uv:u,indices:h})}const Ei={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function bi(e={}){var t=e.origin||[0,0,0],s=t[0],n=t[1],i=t[2],a=e.size||1,r=[],l=[],o=e.text;m.isNumeric(o)&&(o=""+o);for(var c,u,h,p,A,d,f,I,y,v=(o||"").split("\n"),w=0,g=0,T=.04,E=0;E<v.length;E++){c=0,h=(u=v[E]).length;for(var b=0;b<h;b++)if(p=Ei[u.charAt(b)]){A=1,d=-1,f=-1,I=p.points.length;for(var D=0;D<I;D++)-1!==(y=p.points[D])[0]||-1!==y[1]?(r.push(c+y[0]*a*T+s),r.push(g+y[1]*a*T+n),r.push(0+i),-1===d?d=w:(-1===f||(d=f),f=w),w++,A?A=!1:(l.push(d),l.push(f))):A=1;c+=p.width*T*a}g-=35*T*a}return m.apply(e,{primitive:"lines",positions:r,indices:l})}class Di extends r{constructor(e,t){super("AxisGizmo",e,t=t||{});const s=e.scene.camera;t.canvasId||t.canvasElement||this.error("Config expected: either 'canvasId' or 'canvasElement'");try{this._axisGizmoScene=new As(e,{canvasId:t.canvasId,canvasElement:t.canvasElement,transparent:!0})}catch(e){return void this.error(e)}const n=this._axisGizmoScene;n.clearLights(),new ft(n,{color:[.45,.45,.5],intensity:.9}),new dt(n,{dir:[-.5,.5,-.6],color:[.8,.8,.7],intensity:1,space:"view"}),new dt(n,{dir:[.5,-.5,-.6],color:[.8,.8,.8],intensity:1,space:"view"});const i=n.camera;s.on("matrix",(function(){const e=s.eye,t=s.look,n=s.up,a=p.mulVec3Scalar(p.normalizeVec3(p.subVec3(e,t,[])),22);i.look=[0,0,0],i.eye=a,i.up=n}));const a=new Rt(n,gi({radiusTop:.01,radiusBottom:.6,height:1.7,radialSegments:20,heightSegments:1,openEnded:!1})),r=new Rt(n,gi({radiusTop:.2,radiusBottom:.2,height:4.5,radialSegments:20,heightSegments:1,openEnded:!1})),l=new St(n,{diffuse:[1,.3,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),o=new St(n,{emissive:[1,.3,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),c=new St(n,{diffuse:[.3,1,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),u=new St(n,{emissive:[.3,1,.3],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),h=new St(n,{diffuse:[.3,.3,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),A=new St(n,{emissive:[.3,.3,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),d=new St(n,{diffuse:[.5,.5,.5],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2});this._meshes=[new vi(n,{geometry:new Rt(n,Ti({radius:9,heightSegments:60,widthSegments:60})),material:new St(n,{diffuse:[0,0,0],emissive:[.1,.1,.1],ambient:[.1,.1,.2],specular:[0,0,0],alpha:.4,alphaMode:"blend",frontface:"cw"}),pickable:!1,collidable:!1,visible:!1!==t.visible}),new vi(n,{geometry:new Rt(n,Ti({radius:1})),material:d,pickable:!1,collidable:!1,visible:!1!==t.visible}),new vi(n,{geometry:a,material:l,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[5,0,0],rotation:[0,0,-90]}),new vi(n,{geometry:r,material:l,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[2,0,0],rotation:[0,0,90]}),new vi(n,{geometry:new Rt(n,bi({text:"X",size:1.5})),material:o,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[7,0,0],billboard:"spherical"}),new vi(n,{geometry:a,material:c,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,5,0]}),new vi(n,{geometry:r,material:c,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,2,0]}),new vi(n,{geometry:new Rt(n,bi({text:"Y",size:1.5})),material:u,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,7,0],billboard:"spherical"}),new vi(n,{geometry:a,material:h,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,0,5],rotation:[90,0,0]}),new vi(n,{geometry:r,material:h,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,0,2],rotation:[90,0,0]}),new vi(n,{geometry:new Rt(n,bi({text:"Z",size:1.5})),material:A,pickable:!1,collidable:!1,visible:!1!==t.visible,position:[0,0,7],billboard:"spherical"})]}setVisible(e){for(let t=0;t<this._meshes.length;t++)this._meshes[t].visible=e}destroy(){this._axisGizmoCanvas=null,this._axisGizmoScene.destroy(),this._axisGizmoScene=null,super.destroy()}}class Pi extends _{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new We({active:!0,pos:p.vec3(),dir:p.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-p.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-p.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-p.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const Ri=p.vec4(4),Ci=p.vec4(),_i=p.vec4(),Bi=p.vec3([1,0,0]),Oi=p.vec3([0,1,0]),Si=p.vec3([0,0,1]),Ni=p.vec3(3),xi=p.vec3(3),Li=p.identityMat4();class Mi extends _{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=p.vec3(),this._quaternion=p.identityQuaternion(),this._rotation=p.vec3(),this._position=p.vec3(),this._offset=p.vec3(),this._localMatrix=p.identityMat4(),this._worldMatrix=p.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let s=0,n=e.length;s<n;s++)this.addChild(e[s],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=p.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,s=this._children.length;t<s;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,s=this._children.length;e<s;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,s=this._children.length;t<s;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)p.mulMat4(this._parentNode.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._children)for(let t=0,s=e._children.length;t<s;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=p.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;p.collapseAABB3(this._aabb);for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e.collidable&&p.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+m.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,s=this._children.length;t<s;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+m.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),p.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),p.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=p.identityMat4()),this._localMatrix.set(e||Li),p.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=p.identityMat4()),p.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 Ri[0]=e[0],Ri[1]=e[1],Ri[2]=e[2],Ri[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(Ri,Ci),p.mulQuaternions(this.quaternion,Ci,_i),this.quaternion=_i,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ri[0]=e[0],Ri[1]=e[1],Ri[2]=e[2],Ri[3]=t*p.DEGTORAD,p.angleAxisToQuaternion(Ri,Ci),p.mulQuaternions(Ci,this.quaternion,Ci),this}rotateX(e){return this.rotate(Bi,e)}rotateY(e){return this.rotate(Oi,e)}rotateZ(e){return this.rotate(Si,e)}translate(e,t){return p.vec3ApplyQuaternion(this.quaternion,e,Ni),p.mulVec3Scalar(Ni,t,xi),p.addVec3(this.position,xi,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Bi,e)}translateY(e){return this.translate(Oi,e)}translateZ(e){return this.translate(Si,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,n=e.length;s<n;s++)t=e[s],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}class Fi extends _t{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new We({type:"LambertMaterial",ambient:p.vec3([1,1,1]),color:p.vec3([1,1,1]),emissive:p.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const Hi={opaque:0,mask:1,blend:2},Ui=["opaque","mask","blend"];class Gi extends _t{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new We({type:"MetallicMaterial",baseColor:p.vec4([1,1,1]),emissive:p.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=Hi[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Ui[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const Vi={opaque:0,mask:1,blend:2},ji=["opaque","mask","blend"];class ki extends _t{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new We({type:"SpecularMaterial",diffuse:p.vec3([1,1,1]),emissive:p.vec3([0,0,0]),specular:p.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=Vi[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return ji[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}function Qi(e,t,s=null){let n;const i=t;if(1009===i)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(1015===i)return e.FLOAT;if(1016===i)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1023===i)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(1028===i)return e.RED;if(1022===i)return e.RGBA;if(1029===i)return e.RED_INTEGER;if(1030===i)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i)if(3001===s){const t=Ve(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===i)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=Ve(e,"WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===i)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){const t=Ve(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===i)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i){const t=Ve(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===i||37496===i){const t=Ve(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===i)return 3001===s?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){const t=Ve(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===i){const t=Ve(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===i)return 3001===s?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===i?e.UNSIGNED_INT_24_8:1e3===i?e.REPEAT:1001===i?e.CLAMP_TO_EDGE:1004===i||1005===i?e.NEAREST_MIPMAP_LINEAR:1007===i?e.LINEAR_MIPMAP_NEAREST:1008===i?e.LINEAR_MIPMAP_LINEAR:1003===i?e.NEAREST:1006===i?e.LINEAR:null}const Wi=new Uint8Array([0,0,0,1]);class zi{constructor({gl:e,target:t,format:s,type:n,wrapS:i,wrapT:a,wrapR:r,encoding:l,preloadColor:o,premultiplyAlpha:c,flipY:u}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!u,this.unpackAlignment=4,this.wrapS=i||1e3,this.wrapT=a||1e3,this.wrapR=r||1e3,this.encoding=l||3001,this.texture=e.createTexture(),o&&this.setPreloadColor(o),this.allocated=!0}setPreloadColor(e){e?(Wi[0]=Math.floor(255*e[0]),Wi[1]=Math.floor(255*e[1]),Wi[2]=Math.floor(255*e[2]),Wi[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Wi[0]=0,Wi[1]=0,Wi[2]=0,Wi[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let s=0,n=e.length;s<n;s++)t.texImage2D(e[s],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const s=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let n=!1;s.bindTexture(this.target,this.texture);const i=s.getParameter(s.UNPACK_FLIP_Y_WEBGL);s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY);const a=s.getParameter(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL);s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const r=s.getParameter(s.UNPACK_ALIGNMENT);s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment);const l=s.getParameter(s.UNPACK_COLORSPACE_CONVERSION_WEBGL);s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=Qi(s,this.minFilter);s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,o),o!==s.NEAREST_MIPMAP_NEAREST&&o!==s.LINEAR_MIPMAP_NEAREST&&o!==s.NEAREST_MIPMAP_LINEAR&&o!==s.LINEAR_MIPMAP_LINEAR||(n=!0);const c=Qi(s,this.magFilter);c&&s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,c);const u=Qi(s,this.wrapS);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,u);const h=Qi(s,this.wrapT);h&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,h);const p=Qi(s,this.format,this.encoding),A=Qi(s,this.type),d=Ki(s,this.internalFormat,p,A,this.encoding,!1);if(this.target===s.TEXTURE_CUBE_MAP){if(m.isArray(e)){const t=e,n=[s.TEXTURE_CUBE_MAP_POSITIVE_X,s.TEXTURE_CUBE_MAP_NEGATIVE_X,s.TEXTURE_CUBE_MAP_POSITIVE_Y,s.TEXTURE_CUBE_MAP_NEGATIVE_Y,s.TEXTURE_CUBE_MAP_POSITIVE_Z,s.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,i=n.length;e<i;e++)s.texImage2D(n[e],0,d,p,A,t[e])}}else s.texImage2D(s.TEXTURE_2D,0,d,p,A,e);n&&s.generateMipmap(this.target),s.bindTexture(this.target,null),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a),s.pixelStorei(s.UNPACK_ALIGNMENT,r),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l)}setCompressedData({mipmaps:e,props:t={}}){const s=this.gl,n=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),s.activeTexture(s.TEXTURE0+0),s.bindTexture(this.target,this.texture);let i=e.length>1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const a=Qi(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);const r=Qi(s,this.wrapT);if(r&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,r),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=Qi(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}i?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Yi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Yi(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Qi(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Qi(s,this.magFilter)));const l=Qi(s,this.format,this.encoding),o=Qi(s,this.type),c=Ki(s,this.internalFormat,l,o,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,c,e[0].width,e[0].height);for(let t=0,n=e.length;t<n;t++){const n=e[t];1023!==this.format?null!==l?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,n.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):s.texSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,o,n.data)}s.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const s=Qi(t,e.minFilter);s&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,s),s!==t.NEAREST_MIPMAP_NEAREST&&s!==t.LINEAR_MIPMAP_NEAREST&&s!==t.NEAREST_MIPMAP_LINEAR&&s!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const s=Qi(t,e.magFilter);s&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,s))}if(void 0!==e.wrapS){const s=Qi(t,e.wrapS);s&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,s))}if(void 0!==e.wrapT){const s=Qi(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function Ki(e,t,s,n,i,a=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let r=s;return s===e.RED&&(n===e.FLOAT&&(r=e.R32F),n===e.HALF_FLOAT&&(r=e.R16F),n===e.UNSIGNED_BYTE&&(r=e.R8)),s===e.RG&&(n===e.FLOAT&&(r=e.RG32F),n===e.HALF_FLOAT&&(r=e.RG16F),n===e.UNSIGNED_BYTE&&(r=e.RG8)),s===e.RGBA&&(n===e.FLOAT&&(r=e.RGBA32F),n===e.HALF_FLOAT&&(r=e.RGBA16F),n===e.UNSIGNED_BYTE&&(r=3001===i&&!1===a?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT_4_4_4_4&&(r=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(r=e.RGB5_A1)),r!==e.R16F&&r!==e.R32F&&r!==e.RG16F&&r!==e.RG32F&&r!==e.RGBA16F&&r!==e.RGBA32F||Ve(e,"EXT_color_buffer_float"),r}function Yi(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Xi(e){if(!qi(e.width)||!qi(e.height)){const t=document.createElement("canvas");t.width=Ji(e.width),t.height=Ji(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function qi(e){return 0==(e&e-1)}function Ji(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Zi extends _{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new We({texture:new zi({gl:this.scene.canvas.gl}),matrix:p.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=p.vec2([0,0]),this._scale=p.vec2([1,1]),this._rotate=p.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new zi({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=p.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=p.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?p.mulMat4(t,s):s),0!==this._rotate&&(s=p.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?p.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Xi(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=Xi(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}class $i extends _{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new We({edgeColor:p.vec3([0,0,0]),centerColor:p.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const ea=d.memory,ta=p.AABB3();class sa extends It{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new We({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=p.OBB3();const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var i;if(t.positionsDecodeMatrix);else{const e=bt.getPositionsBounds(t.positions),a=bt.compressPositions(t.positions,e.min,e.max);i=a.quantized,s.positionsDecodeMatrix=a.decodeMatrix,s.positionsBuf=new De(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),ea.positions+=s.positionsBuf.numItems,p.positions3ToAABB3(t.positions,this._aabb),p.positions3ToAABB3(i,ta,s.positionsDecodeMatrix),p.AABB3ToOBB3(ta,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new De(n,n.ARRAY_BUFFER,e,e.length,4,n.STATIC_DRAW),ea.colors+=s.colorsBuf.numItems}if(t.uv){const e=bt.getUVBounds(t.uv),i=bt.compressUVs(t.uv,e.min,e.max),a=i.quantized;s.uvDecodeMatrix=i.decodeMatrix,s.uvBuf=new De(n,n.ARRAY_BUFFER,a,a.length,2,n.STATIC_DRAW),ea.uvs+=s.uvBuf.numItems}if(t.normals){const e=bt.compressNormals(t.normals);let i=s.compressGeometry;s.normalsBuf=new De(n,n.ARRAY_BUFFER,e,e.length,3,n.STATIC_DRAW,i),ea.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,e,e.length,1,n.STATIC_DRAW),ea.indices+=s.indicesBuf.numItems;const a=yt(i,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),ea.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),ea.meshes--}}var na={};function ia(e,t={}){return new Promise((function(s,n){t.src||(console.error("load3DSGeometry: Parameter expected: src"),n());var i=e.canvas.spinner;i.processes++,m.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),i.processes--,n());var a=na.parse.from3DS(e).edit.objects[0].mesh,r=a.vertices,l=a.uvt,o=a.indices;i.processes--,s(m.apply(t,{primitive:"triangles",positions:r,normals:null,uv:l,indices:o}))}),(function(e){console.error("load3DSGeometry: "+e),i.processes--,n()}))}))}function aa(e,t={}){return new Promise((function(s,n){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),n());var i=e.canvas.spinner;i.processes++,m.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),i.processes--,n());for(var a=na.parse.fromOBJ(e),r=na.edit.unwrap(a.i_verts,a.c_verts,3),l=na.edit.unwrap(a.i_norms,a.c_norms,3),o=na.edit.unwrap(a.i_uvt,a.c_uvt,2),c=new Int32Array(a.i_verts.length),u=0;u<a.i_verts.length;u++)c[u]=u;i.processes--,s(m.apply(t,{primitive:"triangles",positions:r,normals:l.length>0?l:null,autoNormals:0===l.length,uv:o,indices:c}))}),(function(e){console.error("loadOBJGeometry: "+e),i.processes--,n()}))}))}function ra(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let n=e.zSize||1;n<0&&(console.error("negative zSize not allowed - will invert"),n*=-1);const i=e.center,a=i?i[0]:0,r=i?i[1]:0,l=i?i[2]:0,o=-t+a,c=-s+r,u=-n+l,h=t+a,p=s+r,A=n+l;return m.apply(e,{primitive:"lines",positions:[o,c,u,o,c,A,o,p,u,o,p,A,h,c,u,h,c,A,h,p,u,h,p,A],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function la(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let s=e.divisions||1;s<0&&(console.error("negative divisions not allowed - will invert"),s*=-1),s<1&&(s=1),t=t||10,s=s||10;const n=t/s,i=t/2,a=[],r=[];let l=0;for(let e=0,t=-i;e<=s;e++,t+=n)a.push(-i),a.push(0),a.push(t),a.push(i),a.push(0),a.push(t),a.push(t),a.push(0),a.push(-i),a.push(t),a.push(0),a.push(i),r.push(l++),r.push(l++),r.push(l++),r.push(l++);return m.apply(e,{primitive:"lines",positions:a,indices:r})}function oa(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let n=e.xSegments||1;n<0&&(console.error("negative xSegments not allowed - will invert"),n*=-1),n<1&&(n=1);let i=e.xSegments||1;i<0&&(console.error("negative zSegments not allowed - will invert"),i*=-1),i<1&&(i=1);const a=e.center,r=a?a[0]:0,l=a?a[1]:0,o=a?a[2]:0,c=t/2,u=s/2,h=Math.floor(n)||1,p=Math.floor(i)||1,A=h+1,d=p+1,f=t/h,I=s/p,y=new Float32Array(A*d*3),v=new Float32Array(A*d*3),w=new Float32Array(A*d*2);let g,T,E,b,D,P,R,C=0,_=0;for(g=0;g<d;g++){const e=g*I-u;for(T=0;T<A;T++)E=T*f-c,y[C]=E+r,y[C+1]=l,y[C+2]=-e+o,v[C+2]=-1,w[_]=T/h,w[_+1]=(p-g)/p,C+=3,_+=2}C=0;const B=new(y.length/3>65535?Uint32Array:Uint16Array)(h*p*6);for(g=0;g<p;g++)for(T=0;T<h;T++)b=T+A*g,D=T+A*(g+1),P=T+1+A*(g+1),R=T+1+A*g,B[C]=R,B[C+1]=D,B[C+2]=b,B[C+3]=R,B[C+4]=P,B[C+5]=D,C+=6;return m.apply(e,{positions:y,normals:v,uv:w,indices:B})}function ca(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let s=e.tube||.3;s<0&&(console.error("negative tube not allowed - will invert"),s*=-1);let n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<4&&(n=4);let i=e.tubeSegments||24;i<0&&(console.error("negative tubeSegments not allowed - will invert"),i*=-1),i<4&&(i=4);let a=e.arc||2*Math.PI;a<0&&(console.warn("negative arc not allowed - will invert"),a*=-1),a>360&&(a=360);const r=e.center;let l=r?r[0]:0,o=r?r[1]:0;const c=r?r[2]:0,u=[],h=[],A=[],d=[];let f,I,y,v,w,g,T,E,b,D,P,R;for(E=0;E<=i;E++)for(T=0;T<=n;T++)f=T/n*a,I=.785398+E/i*Math.PI*2,l=t*Math.cos(f),o=t*Math.sin(f),y=(t+s*Math.cos(I))*Math.cos(f),v=(t+s*Math.cos(I))*Math.sin(f),w=s*Math.sin(I),u.push(y+l),u.push(v+o),u.push(w+c),A.push(1-T/n),A.push(E/i),g=p.normalizeVec3(p.subVec3([y,v,w],[l,o,c],[]),[]),h.push(g[0]),h.push(g[1]),h.push(g[2]);for(E=1;E<=i;E++)for(T=1;T<=n;T++)b=(n+1)*E+T-1,D=(n+1)*(E-1)+T-1,P=(n+1)*(E-1)+T,R=(n+1)*E+T,d.push(b),d.push(D),d.push(P),d.push(P),d.push(R),d.push(b);return m.apply(e,{positions:u,normals:h,uv:A,indices:d})}na.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},na.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(na.parse._buffToStr(e));window.location.href=s},na.clone=function(e){return JSON.parse(JSON.stringify(e))},na.bin={},na.bin.f=new Float32Array(1),na.bin.fb=new Uint8Array(na.bin.f.buffer),na.bin.rf=function(e,t){for(var s=na.bin.f,n=na.bin.fb,i=0;i<4;i++)n[i]=e[t+i];return s[0]},na.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},na.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},na.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},na.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},na.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},na.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},na.parse={},na.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",n=0;n<t.length;n++)s=s.concat(String.fromCharCode(t[n]));return s},na.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),s=new Uint8Array(t),n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t},na.parse._readLine=function(e,t){for(var s="";10!=e[t];)s+=String.fromCharCode(e[t++]);return s},na.parse.fromJSON=function(e){return JSON.parse(na.parse._buffToStr(e))},na.parse.toJSON=function(e){var t=JSON.stringify(e);return na.parse._strToBuff(t)},na.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},s={from:0,to:0},n=0,i=new Uint8Array(e);n<i.length;){var a=na.parse._readLine(i,n);n+=a.length+1;var r=(a=(a=a.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==r[0]&&(s.to=t.i_verts.length,null==t.groups[r[1]]&&(t.groups[r[1]]={from:t.i_verts.length,to:0}),s=t.groups[r[1]]),"v"==r[0]){var l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_verts.push(l,o,c)}if("vt"==r[0]){l=parseFloat(r[1]),o=1-parseFloat(r[2]);t.c_uvt.push(l,o)}if("vn"==r[0]){l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_norms.push(l,o,c)}if("f"==r[0]){var u=r[1].split("/"),h=r[2].split("/"),p=r[3].split("/"),A=parseInt(u[0])-1,d=parseInt(h[0])-1,f=parseInt(p[0])-1,I=parseInt(u[1])-1,y=parseInt(h[1])-1,m=parseInt(p[1])-1,v=parseInt(u[2])-1,w=parseInt(h[2])-1,g=parseInt(p[2])-1,T=t.c_verts.length/3,E=t.c_uvt.length/2,b=t.c_norms.length/3;if(A<0&&(A=T+A+1),d<0&&(d=T+d+1),f<0&&(f=T+f+1),I<0&&(I=E+I+1),y<0&&(y=E+y+1),m<0&&(m=E+m+1),v<0&&(v=b+v+1),w<0&&(w=b+w+1),g<0&&(g=b+g+1),t.i_verts.push(A,d,f),t.i_uvt.push(I,y,m),t.i_norms.push(v,w,g),5==r.length){var D=r[4].split("/"),P=parseInt(D[0])-1,R=parseInt(D[1])-1,C=parseInt(D[2])-1;P<0&&(P=T+P+1),R<0&&(R=E+R+1),C<0&&(C=b+C+1),t.i_verts.push(A,f,P),t.i_uvt.push(I,m,R),t.i_norms.push(v,g,C)}}}return s.to=t.i_verts.length,t},na.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},s={};s.ident=na.bin.ril(e,0),s.version=na.bin.ril(e,4),s.skinwidth=na.bin.ril(e,8),s.skinheight=na.bin.ril(e,12),s.framesize=na.bin.ril(e,16),s.num_skins=na.bin.ril(e,20),s.num_vertices=na.bin.ril(e,24),s.num_st=na.bin.ril(e,28),s.num_tris=na.bin.ril(e,32),s.num_glcmds=na.bin.ril(e,36),s.num_frames=na.bin.ril(e,40),s.offset_skins=na.bin.ril(e,44),s.offset_st=na.bin.ril(e,48),s.offset_tris=na.bin.ril(e,52),s.offset_frames=na.bin.ril(e,56),s.offset_glcmds=na.bin.ril(e,60),s.offset_end=na.bin.ril(e,64);var n=s.offset_st;t.c_uvt=[];for(var i=0;i<s.num_st;i++){var a=na.bin.rsl(e,n)/s.skinwidth,r=na.bin.rsl(e,n+2)/s.skinheight;t.c_uvt.push(a,r),n+=4}n=s.offset_tris;var l=[],o=[];t.i_verts=l,t.i_uvt=o;for(i=0;i<s.num_tris;i++)l.push(na.bin.rsl(e,n),na.bin.rsl(e,n+2),na.bin.rsl(e,n+4)),o.push(na.bin.rsl(e,n+6),na.bin.rsl(e,n+8),na.bin.rsl(e,n+10)),n+=12;n=s.offset_skins;t.skins=[];for(i=0;i<s.num_skins;i++)t.skins.push(na.bin.rASCII0(e,n)),n+=64;n=s.offset_frames;t.frames=[];var c=na.parse.fromMD2._normals;for(i=0;i<s.num_frames;i++){var u={},h=na.bin.rf(e,n),p=na.bin.rf(e,n+4),A=na.bin.rf(e,n+8);n+=12;var d=na.bin.rf(e,n),f=na.bin.rf(e,n+4),I=na.bin.rf(e,n+8);n+=12,u.name=na.bin.rASCII0(e,n),n+=16,u.verts=[],u.norms=[];for(var y=0;y<s.num_vertices;y++)u.verts.push(e[n]*h+d,e[n+1]*p+f,e[n+2]*A+I),u.norms.push(c[3*e[n+3]],c[3*e[n+3]+1],c[3*e[n+3]+2]),n+=4;t.frames.push(u)}return t},na.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],na.parse.fromCollada=function(e){var t=na.parse._buffToStr(e),s=(new DOMParser).parseFromString(t,"text/xml"),n={},i=(s=s.childNodes[0]).getElementsByTagName("asset")[0],a=s.getElementsByTagName("library_geometries")[0],r=s.getElementsByTagName("library_images")[0],l=s.getElementsByTagName("library_materials")[0],o=s.getElementsByTagName("library_effects")[0];return i&&(n.asset=na.parse.fromCollada._asset(i)),a&&(n.geometries=na.parse.fromCollada._libGeometries(a)),r&&(n.images=na.parse.fromCollada._libImages(r)),l&&(n.materials=na.parse.fromCollada._libMaterials(l)),o&&(n.effects=na.parse.fromCollada._libEffects(o)),n},na.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},na.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],s=0;s<e.length;s++){var n=e[s],i=na.parse.fromCollada._getMesh(n.getElementsByTagName("mesh")[0]);t.push(i)}return t},na.parse.fromCollada._getMesh=function(e){for(var t={},s=e.getElementsByTagName("source"),n=t.sources={},i=0;i<s.length;i++){for(var a=s[i].getElementsByTagName("float_array")[0].textContent.split(" "),r=a.length-(""==a[a.length-1]?1:0),l=new Array(r),o=0;o<r;o++)l[o]=parseFloat(a[o]);n[s[i].getAttribute("id")]=l}t.triangles=[];var c=e.getElementsByTagName("triangles");if(null==c)return t;for(i=0;i<c.length;i++){var u={},h=c[i];u.material=h.getAttribute("material");var p=h.getElementsByTagName("input"),A=[];for(o=0;o<p.length;o++){var d=p[o];l=[];A[parseInt(d.getAttribute("offset"))]=l;var f=d.getAttribute("semantic");u["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):d.getAttribute("source").substring(1),u["i_"+f]=l,n[u["s_"+f]]}var I=h.getElementsByTagName("p")[0].textContent.split(" "),y=3*Math.floor(I.length/3);for(o=0;o<y;o++)A[o%p.length].push(parseInt(I[o]));t.triangles.push(u)}return t},na.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("id")]=e[s].getElementsByTagName("init_from")[0].textContent;return t},na.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("name")]=e[s].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},na.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},s=0;s<e.length;s++){for(var n={},i=e[s].getElementsByTagName("newparam"),a=0;a<i.length;a++){var r=i[a].getElementsByTagName("surface")[0];r&&(n.surface=r.getElementsByTagName("init_from")[0].textContent)}t[e[s].getAttribute("id")]=n}return t},na.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=na.bin.rsl(e,0))return null;for(var s=na.bin.ril(e,2),n=6;n<s;){var i=na.bin.rsl(e,n),a=na.bin.ril(e,n+2);15677==i&&(t.edit=na.parse.from3DS._edit3ds(e,n,a)),45056==i&&(t.keyf=na.parse.from3DS._keyf3ds(e,n,a)),n+=a}return t},na.parse.from3DS._edit3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);16384==a&&(null==n.objects&&(n.objects=[]),n.objects.push(na.parse.from3DS._edit_object(e,i,r))),i+=r}return n},na.parse.from3DS._keyf3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);45058==a&&(null==n.desc&&(n.desc=[]),n.desc.push(na.parse.from3DS._keyf_objdes(e,i,r))),i+=r}return n},na.parse.from3DS._keyf_objdes=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);45072==a&&(n.hierarchy=na.parse.from3DS._keyf_objhierarch(e,i,r)),45073==a&&(n.dummy_name=na.bin.rASCII0(e,i+6)),i+=r}return n},na.parse.from3DS._keyf_objhierarch=function(e,t,s){var n={},i=t+6;return n.name=na.bin.rASCII0(e,i),i+=n.name.length+1,n.hierarchy=na.bin.rsl(e,i+4),n},na.parse.from3DS._edit_object=function(e,t,s){var n={},i=t+6;for(n.name=na.bin.rASCII0(e,i),i+=n.name.length+1;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);16640==a&&(n.mesh=na.parse.from3DS._obj_trimesh(e,i,r)),i+=r}return n},na.parse.from3DS._obj_trimesh=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=na.bin.rsl(e,i),r=na.bin.ril(e,i+2);16656==a&&(n.vertices=na.parse.from3DS._tri_vertexl(e,i,r)),16672==a&&(n.indices=na.parse.from3DS._tri_facel1(e,i,r)),16704==a&&(n.uvt=na.parse.from3DS._tri_mappingcoors(e,i,r)),16736==a&&(n.local=na.parse.from3DS._tri_local(e,i,r)),i+=r}return n},na.parse.from3DS._tri_vertexl=function(e,t,s){var n=[],i=t+6,a=na.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(na.bin.rf(e,i)),n.push(na.bin.rf(e,i+4)),n.push(na.bin.rf(e,i+8)),i+=12;return n},na.parse.from3DS._tri_facel1=function(e,t,s){var n=[],i=t+6,a=na.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(na.bin.rsl(e,i)),n.push(na.bin.rsl(e,i+2)),n.push(na.bin.rsl(e,i+4)),i+=8;return n},na.parse.from3DS._tri_mappingcoors=function(e,t,s){var n=[],i=t+6,a=na.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(na.bin.rf(e,i)),n.push(1-na.bin.rf(e,i+4)),i+=8;return n},na.parse.from3DS._tri_local=function(e,t,s){var n={},i=t+6;return n.X=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n.Y=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n.Z=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n.C=[na.bin.rf(e,i),na.bin.rf(e,i+4),na.bin.rf(e,i+8)],i+=12,n},na.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},s={};return s.id=na.bin.ril(e,0),s.verS=na.bin.ril(e,4),s.texS=na.bin.ril(e,8),s.indS=na.bin.ril(e,12),s.verO=na.bin.ril(e,16),s.verL=na.bin.ril(e,20),s.texO=na.bin.ril(e,24),s.texL=na.bin.ril(e,28),s.indO=na.bin.ril(e,32),s.indL=na.bin.ril(e,36),0!=s.verO&&(t.vertices=na.parse.fromBIV._readFloats(e,s.verO,s.verL)),0!=s.texO&&(t.uvt=na.parse.fromBIV._readFloats(e,s.texO,s.texL)),0!=s.indO&&(t.indices=na.parse.fromBIV._readInts(e,s.indO,s.indL,s.indS)),t},na.parse.toBIV=function(e){for(var t=0,s=0;s<e.indices.length;s++)t=Math.max(t,e.indices[s]);var n=32;t<=65535&&(n=16);var i=40;e.vertices&&(i+=4*e.vertices.length),e.uvt&&(i+=4*e.uvt.length),e.indices&&(i+=e.indices.length*n/8);var a=new Uint8Array(i);na.bin.wil(a,0,1769365870),na.bin.wil(a,4,32),na.bin.wil(a,8,32),na.bin.wil(a,12,n);var r=40;return e.vertices&&(na.bin.wil(a,16,r),na.bin.wil(a,20,4*e.vertices.length),na.parse.fromBIV._writeFloats(a,r,e.vertices),r+=4*e.vertices.length),e.uvt&&(na.bin.wil(a,24,r),na.bin.wil(a,28,4*e.uvt.length),na.parse.fromBIV._writeFloats(a,r,e.uvt),r+=4*e.uvt.length),e.indices&&(na.bin.wil(a,32,r),na.bin.wil(a,36,4*e.indices.length),na.parse.fromBIV._writeInts(a,r,e.indices,n)),a.buffer},na.parse.fromBIV._readFloats=function(e,t,s){for(var n=[],i=0;i<s/4;i++)n.push(na.bin.rf(e,t+4*i));return n},na.parse.fromBIV._writeFloats=function(e,t,s){for(var n=0;n<s.length;n++)na.bin.wf(e,t+4*n,s[n])},na.parse.fromBIV._readInts=function(e,t,s,n){for(var i=[],a=0;a<s/4;a++)16==n&&i.push(na.bin.rsl(e,t+2*a)),32==n&&i.push(na.bin.ril(e,t+4*a));return i},na.parse.fromBIV._writeInts=function(e,t,s,n){for(var i=0;i<s.length;i++)16==n&&na.bin.wsl(e,t+2*i,s[i]),32==n&&na.bin.wil(e,t+4*i,s[i])},na.gen={},na.gen.Plane=function(e,t,s,n){s||(s=1),n||(n=1);for(var i={verts:[],inds:[],uvt:[]},a=e+1,r=t+1,l=0;l<r;l++)for(var o=0;o<a;o++){var c=o*(2/e)-1,u=l*(2/t)-1;i.verts.push(c,u,0),i.uvt.push(s*o/e,n*l/t),l<t&&o<e&&i.inds.push(l*a+o,l*a+o+1,(l+1)*a+o,l*a+o+1,(l+1)*a+o,(l+1)*a+o+1)}return i},na.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},na.gen.Sphere=function(e,t){for(var s={verts:[],inds:[],uvt:[]},n=e+1,i=t+1,a=0;a<i;a++)for(var r=0;r<n;r++){var l=-Math.PI/2+a*Math.PI/t,o=2*r*Math.PI/e,c=Math.cos(l)*Math.cos(o),u=Math.sin(l),h=Math.cos(l)*Math.sin(o);s.verts.push(c,u,h),s.uvt.push(r/e,a/t),a<t&&r<e&&s.inds.push(n*a+r,n*a+r+1,n*(a+1)+r,n*a+r+1,n*(a+1)+r,n*(a+1)+r+1)}return s},na.mat={},na.mat.scale=function(e,t,s){return[e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1]},na.mat.translate=function(e,t,s){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1]},na.mat.rotateDeg=function(e,t,s){var n=Math.PI/180;return na.mat.rotate(e*n,t*n,s*n)},na.mat.rotate=function(e,t,s){var n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i=e,a=t,r=s,l=Math.cos(i),o=Math.cos(a),c=Math.cos(r),u=Math.sin(i),h=Math.sin(a),p=Math.sin(r);return n[0]=o*c,n[1]=-o*p,n[2]=h,n[4]=l*p+u*h*c,n[5]=l*c-u*h*p,n[6]=-u*o,n[8]=u*p-l*h*c,n[9]=u*c+l*h*p,n[10]=l*o,n},na.edit={},na.edit.interpolate=function(e,t,s,n){for(var i=0;i<e.length;i++)s[i]=e[i]+n*(t[i]-e[i])},na.edit.transform=function(e,t){for(var s=0;s<e.length;s+=3){var n=e[s],i=e[s+1],a=e[s+2];e[s+0]=t[0]*n+t[4]*i+t[8]*a+t[12],e[s+1]=t[1]*n+t[5]*i+t[9]*a+t[13],e[s+2]=t[2]*n+t[6]*i+t[10]*a+t[14]}},na.edit.unwrap=function(e,t,s){for(var n=new Array(Math.floor(e.length/3)*s),i=0;i<e.length;i++)for(var a=0;a<s;a++)n[i*s+a]=t[e[i]*s+a];return n},na.edit.remap=function(e,t,s,n){for(var i=new Array(s.length),a=0;a<e.length;a++)for(var r=0;r<n;r++)i[t[a]*n+r]=s[e[a]*n+r];return i},na.utils={},na.utils.getAABB=function(e){var t,s,n,i,a,r;i=a=r=-(t=s=n=999999999);for(var l=0;l<e.length;l+=3){var o=e[l+0],c=e[l+1],u=e[l+2];o<t&&(t=o),o>i&&(i=o),c<s&&(s=c),c>a&&(a=c),u<n&&(n=u),c>r&&(r=u)}return{min:{x:t,y:s,z:n},max:{x:i,y:a,z:r}}};class ua extends _{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=p.vec3(t.pos||[0,0,0]),this._up=p.vec3(t.up||[0,1,0]),this._normal=p.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=p.vec3(),this._rtcPos=p.vec3(),this._imageSize=p.vec2(),this._texture=new Zi(this),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Mi(this,{matrix:p.inverseMat4(p.lookAtMat4v(this._pos,p.subVec3(this._pos,this._normal,p.mat4()),this._up,p.mat4())),children:[this._bitmapMesh=new vi(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Rt(this,oa({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new St(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height*e,1,this._height]}}class ha extends _{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],this._origin=p.vec3(t.origin||[0,0,0]),t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._mesh=new vi(this,{visible:t.visible,clippable:t.clippable,collidable:t.collidable,geometry:new sa(this,{primitive:"lines",positions:this._positions,indices:this._indices,origin:t.origin}),material:new St(this,{diffuse:t.color||[0,0,0],emissive:t.color||[0,0,0]})}),this.scene._lineSetCreated(this)}set visible(e){this._mesh.visible=e}get visible(){return this._mesh.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}const pa=p.vec3(),Aa=p.vec3(),da=p.vec3(),fa=p.vec3();class Ia extends r{constructor(e,t={}){super("BCFViewpoints",e,t),this.originatingSystem=t.originatingSystem||"xeokit.io",this.authoringTool=t.authoringTool||"xeokit.io"}getViewpoint(e={}){const t=this.viewer.scene,s=t.camera,n=t.realWorldOffset,i=!0===e.reverseClippingPlanes;let a={},r=p.normalizeVec3(p.subVec3(s.look,s.eye,p.vec3())),l=s.eye,o=s.up;s.yUp&&(r=va(r),l=va(l),o=va(o));const c=ya(p.addVec3(l,n));"ortho"===s.projection?a.orthogonal_camera={camera_view_point:c,camera_direction:ya(r),camera_up_vector:ya(o),view_to_world_scale:s.ortho.scale}:a.perspective_camera={camera_view_point:c,camera_direction:ya(r),camera_up_vector:ya(o),field_of_view:s.perspective.fov};const u=t.sectionPlanes;for(let e in u)if(u.hasOwnProperty(e)){let t=u[e];if(!t.active)continue;let r,l=t.pos;r=i?p.negateVec3(t.dir,p.vec3()):t.dir,s.yUp&&(l=va(l),r=va(r)),p.addVec3(l,n),l=ya(l),r=ya(r),a.clipping_planes||(a.clipping_planes=[]),a.clipping_planes.push({location:l,direction:r})}const h=t.lineSets;for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];a.lines||(a.lines=[]);const s=t.positions,n=t.indices;for(let e=0,t=n.length/2;e<t;e++){const t=n[2*e],i=n[2*e+1];a.lines.push({start_point:{x:s[3*t+0],y:s[3*t+1],z:s[3*t+2]},end_point:{x:s[3*i+0],y:s[3*i+1],z:s[3*i+2]}})}}const A=t.bitmaps;for(let e in A)if(A.hasOwnProperty(e)){let t=A[e],i=t.pos,r=t.normal,l=t.up;s.yUp&&(i=va(i),r=va(r),l=va(l)),p.addVec3(i,n),a.bitmaps||(a.bitmaps=[]),a.bitmaps.push({bitmap_type:t.type,bitmap_data:t.imageData,location:ya(i),normal:ya(r),up:ya(l),height:t.height})}a.components={visibility:{view_setup_hints:{spaces_visible:!!e.spacesVisible,space_boundaries_visible:!!e.spaceBoundariesVisible,openings_visible:!!e.openingsVisible}}};const d=new Set(t.opacityObjectIds),f=new Set(t.xrayedObjectIds),I=new Set(t.colorizedObjectIds),y=Object.values(t.objects).filter((e=>d.has(e.id)||I.has(e.id)||f.has(e.id))).reduce(((e,s)=>{let n,i=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(s.colorize);s.xrayed?(n=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,n=Math.round(255*n).toString(16).padStart(2,"0"),i=n+i):d.has(s.id)&&(n=Math.round(255*s.opacity).toString(16).padStart(2,"0"),i=n+i),e[i]||(e[i]=[]);const a=s.id,r=s.originalSystemId,l={ifc_guid:r,originating_system:this.originatingSystem};return r!==a&&(l.authoring_tool_id=a),e[i].push(l),e}),{}),m=Object.entries(y).map((([e,t])=>({color:e,components:t})));a.components.coloring=m;const v=t.objectIds,w=t.visibleObjects,g=t.visibleObjectIds,T=v.filter((e=>!w[e])),E=t.selectedObjectIds;return e.defaultInvisible||g.length<T.length?(a.components.visibility.exceptions=this._createBCFComponents(g),a.components.visibility.default_visibility=!1):(a.components.visibility.exceptions=this._createBCFComponents(T),a.components.visibility.default_visibility=!0),a.components.selection=this._createBCFComponents(E),!1!==e.snapshot&&(a.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),a}_createBCFComponents(e){const t=this.viewer.scene,s=[];for(let n=0,i=e.length;n<i;n++){const i=e[n],a=t.objects[i];if(a){const e={ifc_guid:a.originalSystemId,originating_system:this.originatingSystem};a.originalSystemId!==i&&(e.authoring_tool_id=i),s.push(e)}}return s}setViewpoint(e,t={}){if(!e)return;const s=this.viewer,n=s.scene,i=n.camera,a=!1!==t.rayCast,r=!1!==t.immediate,l=!1!==t.reset,o=n.realWorldOffset,c=!0===t.reverseClippingPlanes;if(n.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.forEach((function(e){let t=ma(e.location,pa),s=ma(e.direction,pa);c&&p.negateVec3(s),p.subVec3(t,o),i.yUp&&(t=wa(t),s=wa(s)),new Pi(n,{pos:t,dir:s})})),n.clearLines(),e.lines){const t=[],s=[];let i=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),s.push(i++),s.push(i++))})),new ha(n,{positions:t,indices:s,clippable:!1,collidable:!0})}if(n.clearBitmaps(),e.bitmaps&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",s=e.bitmap_data;let a=ma(e.location,Aa),r=ma(e.normal,da),l=ma(e.up,fa),o=e.height||1;t&&s&&a&&r&&l&&(i.yUp&&(a=wa(a),r=wa(r),l=wa(l)),new ua(n,{src:s,type:t,pos:a,normal:r,up:l,clippable:!1,collidable:!0,height:o}))})),l&&(n.setObjectsXRayed(n.xrayedObjectIds,!1),n.setObjectsHighlighted(n.highlightedObjectIds,!1),n.setObjectsSelected(n.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(n.setObjectsVisible(n.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(n.setObjectsVisible(n.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const i=e.components.visibility.view_setup_hints;i&&(!1===i.spaces_visible&&n.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===i.openings_visible&&n.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!1),i.space_boundaries_visible)}e.components.selection&&(n.setObjectsSelected(n.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let s=e.color,n=0,i=!1;8===s.length&&(n=parseInt(s.substring(0,2),16)/256,n<=1&&n>=.95&&(n=1),s=s.substring(2),i=!0);const a=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=a,i&&(e.opacity=n)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let l,c,u,h;if(e.perspective_camera?(l=ma(e.perspective_camera.camera_view_point,pa),c=ma(e.perspective_camera.camera_direction,pa),u=ma(e.perspective_camera.camera_up_vector,pa),i.perspective.fov=e.perspective_camera.field_of_view,h="perspective"):(l=ma(e.orthogonal_camera.camera_view_point,pa),c=ma(e.orthogonal_camera.camera_direction,pa),u=ma(e.orthogonal_camera.camera_up_vector,pa),i.ortho.scale=e.orthogonal_camera.view_to_world_scale,h="ortho"),p.subVec3(l,o),i.yUp&&(l=wa(l),c=wa(c),u=wa(u)),a){const e=n.pick({pickSurface:!0,origin:l,direction:c});c=e?e.worldPos:p.addVec3(l,c,pa)}else c=p.addVec3(l,c,pa);r?(i.eye=l,i.look=c,i.up=u,i.projection=h):s.cameraFlight.flyTo({eye:l,look:c,up:u,duration:t.duration,projection:h})}}_withBCFComponent(e,t,s){const n=this.viewer,i=n.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const a=t.authoring_tool_id,r=i.objects[a];if(r)return void s(r);if(e.updateCompositeObjects){if(n.metaScene.metaObjects[a])return void i.withObjects(n.metaScene.getObjectIDsInSubtree(a),s)}}if(t.ifc_guid){const a=t.ifc_guid,r=i.objects[a];if(r)return void s(r);if(e.updateCompositeObjects){if(n.metaScene.metaObjects[a])return void i.withObjects(n.metaScene.getObjectIDsInSubtree(a),s)}Object.keys(i.models).forEach((t=>{const r=p.globalizeObjectId(t,a),l=i.objects[r];if(l)s(l);else if(e.updateCompositeObjects){n.metaScene.metaObjects[r]&&i.withObjects(n.metaScene.getObjectIDsInSubtree(r),s)}}))}}destroy(){super.destroy()}}function ya(e){return{x:e[0],y:e[1],z:e[2]}}function ma(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function va(e){return new Float64Array([e[0],-e[2],e[1]])}function wa(e){return new Float64Array([e[0],e[2],-e[1]])}var ga=p.vec3();const Ta=(e,t,s,n)=>{var i=e-s,a=t-n;return Math.sqrt(i*i+a*a)};class Ea extends _{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new q(s,t.origin),this._targetMarker=new q(s,t.target),this._originWorld=p.vec3(),this._targetWorld=p.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new Z(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new Z(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthWire=new J(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisWire=new J(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisWire=new J(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisWire=new J(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthLabel=new $(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisLabel=new $(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisLabel=new $(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisLabel=new $(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(p.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0);const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){p.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var n=this._pp,i=this._cp,a=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var r=a.top-t.top,l=a.left-t.left,o=e.canvas.boundary,c=o[2],u=o[3],h=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,I=s.units,y=s.unitsInfo[I].abbrev;for(var A=0,d=n.length;A<d;A+=4)i[h]=l+Math.floor((1+n[A+0]/n[A+3])*c/2),i[h+1]=r+Math.floor((1-n[A+1]/n[A+3])*u/2),h+=2;if(this._originDot.setPos(i[0],i[1]),this._targetDot.setPos(i[6],i[7]),this._lengthWire.setStartAndEnd(i[0],i[1],i[6],i[7]),this._xAxisWire.setStartAndEnd(i[0],i[1],i[2],i[3]),this._yAxisWire.setStartAndEnd(i[2],i[3],i[4],i[5]),this._zAxisWire.setStartAndEnd(i[4],i[5],i[6],i[7]),this.labelsVisible){this._lengthLabel.setPosOnWire(i[0],i[1],i[6],i[7]),this._xAxisLabel.setPosOnWire(i[0],i[1],i[2],i[3]),this._yAxisLabel.setPosOnWire(i[2],i[3],i[4],i[5]),this._zAxisLabel.setPosOnWire(i[4],i[5],i[6],i[7]);const e=this._approximate?" ~ ":" = ";this._length=Math.abs(p.lenVec3(p.subVec3(this._targetWorld,this._originWorld,ga))),this._lengthLabel.setText(e+(this._length*f).toFixed(2)+y);const t=Math.abs(Ta(i[0],i[1],i[2],i[3])),s=Math.abs(Ta(i[2],i[3],i[4],i[5])),n=Math.abs(Ta(i[4],i[5],i[6],i[7])),a=this.plugin.labelMinAxisLength;this._xAxisLabelCulled=t<a,this._yAxisLabelCulled=s<a,this._zAxisLabelCulled=n<a,this._xAxisLabelCulled?this._xAxisLabel.setCulled(!0):(this._xAxisLabel.setText(e+Math.abs((this._targetWorld[0]-this._originWorld[0])*f).toFixed(2)+y),this._xAxisLabel.setCulled(!this.axisVisible)),this._yAxisLabelCulled?this._yAxisLabel.setCulled(!0):(this._yAxisLabel.setText(e+Math.abs((this._targetWorld[1]-this._originWorld[1])*f).toFixed(2)+y),this._yAxisLabel.setCulled(!this.axisVisible)),this._zAxisLabelCulled?this._zAxisLabel.setCulled(!0):(this._zAxisLabel.setText(e+Math.abs((this._targetWorld[2]-this._originWorld[2])*f).toFixed(2)+y),this._zAxisLabel.setCulled(!this.axisVisible))}else this._lengthLabel.setCulled(!0),this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0);this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._xAxisWire.setVisible(this.axisVisible&&this.xAxisVisible),this._yAxisWire.setVisible(this.axisVisible&&this.yAxisVisible),this._zAxisWire.setVisible(this.axisVisible&&this.zAxisVisible),this._lengthWire.setVisible(this.wireVisible),this._lengthLabel.setCulled(!this.wireVisible),this._cpDirty=!1}}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get target(){return this._targetMarker}get length(){this._update();const e=this.plugin.viewer.scene.metrics.scale;return this._length*e}get color(){return this._color}set color(e){this._color=e,this._originDot.setFillColor(e),this._targetDot.setFillColor(e),this._lengthWire.setColor(e),this._lengthLabel.setFillColor(e)}set visible(e){e=void 0!==e?Boolean(e):this.plugin.defaultVisible,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._lengthWire.setVisible(this._visible&&this._wireVisible),this._lengthLabel.setVisible(this._visible&&this._wireVisible);const t=this._visible&&this._axisVisible&&this._xAxisVisible,s=this._visible&&this._axisVisible&&this._yAxisVisible,n=this._visible&&this._axisVisible&&this._zAxisVisible;this._xAxisWire.setVisible(t),this._yAxisWire.setVisible(s),this._zAxisWire.setVisible(n),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._yAxisLabel.setVisible(s&&!this._yAxisLabelCulled),this._zAxisLabel.setVisible(n&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultOriginVisible,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible)}get originVisible(){return this._originVisible}set targetVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultTargetVisible,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible)}get targetVisible(){return this._targetVisible}set axisEnabled(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisEnabled=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._xAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._xAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisEnabled(){return this._axisEnabled}set axisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisVisible=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._yAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._zAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisVisible(){return this._axisVisible}set xAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._xAxisVisible=e;const t=this._visible&&this._axisVisible&&this._xAxisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get xAxisVisible(){return this._xAxisVisible}set yAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._yAxisVisible=e;const t=this._visible&&this._axisVisible&&this._yAxisVisible&&this._axisEnabled;this._yAxisWire.setVisible(t),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get yAxisVisible(){return this._yAxisVisible}set zAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._zAxisVisible=e;const t=this._visible&&this._axisVisible&&this._zAxisVisible&&this._axisEnabled;this._zAxisWire.setVisible(t),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get zAxisVisible(){return this._zAxisVisible}set wireVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultWireVisible,this._wireVisible=e;var t=this._visible&&this._wireVisible;this._lengthLabel.setVisible(t),this._lengthWire.setVisible(t)}get wireVisible(){return this._wireVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._clickable&&this._axisEnabled),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._clickable&&this._axisEnabled),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._clickable&&this._axisEnabled),this._lengthLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._xAxisWire.setHighlighted(e),this._yAxisWire.setHighlighted(e),this._zAxisWire.setHighlighted(e),this._xAxisLabel.setHighlighted(e),this._yAxisLabel.setHighlighted(e),this._zAxisLabel.setHighlighted(e),this._lengthWire.setHighlighted(e),this._lengthLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._xAxisWire.setClickable(this._clickable),this._yAxisWire.setClickable(this._clickable),this._zAxisWire.setClickable(this._clickable),this._lengthWire.setClickable(this._clickable),this._xAxisLabel.setClickable(this._clickable),this._yAxisLabel.setClickable(this._clickable),this._zAxisLabel.setClickable(this._clickable),this._lengthLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene,t=e.metrics;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onMetricsUnits&&t.off(this._onMetricsUnits),this._onMetricsScale&&t.off(this._onMetricsScale),this._onMetricsOrigin&&t.off(this._onMetricsOrigin),this._originDot.destroy(),this._targetDot.destroy(),this._xAxisWire.destroy(),this._yAxisWire.destroy(),this._zAxisWire.destroy(),this._lengthLabel.destroy(),this._xAxisLabel.destroy(),this._yAxisLabel.destroy(),this._zAxisLabel.destroy(),this._lengthWire.destroy(),super.destroy()}}class ba{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const n=Da(e,s);return n?t?Pa(n,t):n:null}translatePlurals(e,t,s){const n=this._messages[this._locale];if(!n)return null;let i=Da(e,n);return i=0===(t=parseInt(""+t,10))?i.zero:t>1?i.other:i.one,i?(i=Pa(i,[t]),s&&(i=Pa(i,s)),i):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];if(n)for(const e in n)if(n.hasOwnProperty(e)){n[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let n=this._eventSubs[t];n||(n={},this._eventSubs[t]=n);const i=this._eventSubIDMap.addItem();n[i]={callback:s},this._eventSubEvents[i]=t;const a=this._events[t];return void 0!==a&&s(a),i}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function Da(e,t){if(t[e])return t[e];const s=e.split(".");let n=t;for(let e=0,t=s.length;n&&e<t;e++){n=n[s[e]]}return n}function Pa(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,s){return"{{"===e?"{":"}}"===e?"}":t[s]}))}class Ra extends _{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var s=e-t,n=e+t;s<0&&(s=0),n>1&&(n=1);var i=this.getPoint(s),a=this.getPoint(n),r=p.subVec3(a,i,[]);return p.normalizeVec3(r,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,s=[];for(t=0;t<=e;t++)s.push(this.getPoint(t/e));return s}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,s,n=[],i=this.getPoint(0),a=0;for(n.push(0),s=1;s<=e;s++)t=this.getPoint(s/e),a+=p.lenVec3(p.subVec3(t,i,[])),n.push(a),i=t;return this.cacheArcLengths=n,n}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var s,n=this._getLengths(),i=0,a=n.length;s=t||e*n[a-1];for(var r,l=0,o=a-1;l<=o;)if((r=n[i=Math.floor(l+(o-l)/2)]-s)<0)l=i+1;else{if(!(r>0)){o=i;break}o=i-1}if(n[i=o]===s)return i/(a-1);var c=n[i];return(i+(s-c)/(n[i+1]-c))/(a-1)}}class Ca extends Ra{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var s=(t.length-1)*e,n=Math.floor(s),i=s-n,a=t[0===n?n:n-1],r=t[n],l=t[n>t.length-2?t.length-1:n+1],o=t[n>t.length-3?t.length-1:n+2],c=p.vec3();return c[0]=p.catmullRomInterpolate(a[0],r[0],l[0],o[0],i),c[1]=p.catmullRomInterpolate(a[1],r[1],l[1],o[1],i),c[2]=p.catmullRomInterpolate(a[2],r[2],l[2],o[2],i),c}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const _a=p.vec3();class Ba extends _{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Ca(this),this._lookCurve=new Ca(this),this._upCurve=new Ca(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,s,n){const i={t:e,eye:t.slice(0),look:s.slice(0),up:n.slice(0)};this._frames.push(i),this._eyeCurve.points.push(i.eye),this._lookCurve.points.push(i.look),this._upCurve.points.push(i.up)}addFrames(e){let t;for(let s=0,n=e.length;s<n;s++)t=e[s],this.addFrame(t.t||0,t.eye,t.look,t.up)}loadFrame(e){const t=this.scene.camera;e=(e/=this._frames[this._frames.length-1].t-this._frames[0].t)<0?0:e>1?1:e,t.eye=this._eyeCurve.getPoint(e,_a),t.look=this._lookCurve.getPoint(e,_a),t.up=this._upCurve.getPoint(e,_a)}sampleFrame(e,t,s,n){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,s),this._upCurve.getPoint(e,n)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=p.vec3();var s=0;this._frames[0].t=0;const n=[];for(let e=1,a=this._frames.length;e<a;e++){var i=p.lenVec3(p.subVec3(this._frames[e].eye,this._frames[e-1].eye,t));n[e]=i,s+=i}for(let t=1,i=this._frames.length;t<i;t++){const i=n[t]/s*e;this._frames[t].t=this._frames[t-1].t+i}}clearFrames(){this._frames=[],this._eyeCurve.points=[],this._lookCurve.points=[],this._upCurve.points=[]}}const Oa=p.vec3(),Sa=p.vec3(),Na=p.vec3(),xa=p.vec3(),La=p.vec3();class Ma extends _{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=p.vec3(),this._eye1=p.vec3(),this._up1=p.vec3(),this._look2=p.vec3(),this._eye2=p.vec3(),this._up2=p.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,s){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=s;const n=this.scene.camera,i=!!e.projection&&e.projection!==n.projection;let a,r,l,o,c;if(this._eye1[0]=n.eye[0],this._eye1[1]=n.eye[1],this._eye1[2]=n.eye[2],this._look1[0]=n.look[0],this._look1[1]=n.look[1],this._look1[2]=n.look[2],this._up1[0]=n.up[0],this._up1[1]=n.up[1],this._up1[2]=n.up[2],this._orthoScale1=n.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)a=e.aabb;else if(6===e.length)a=e;else if(e.eye&&e.look||e.up)r=e.eye,l=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)l=e.look;else{let n=e;if((m.isNumeric(n)||m.isString(n))&&(c=n,n=this.scene.components[c],!n))return this.error("Component not found: "+m.inQuotes(c)),void(t&&(s?t.call(s):t()));i||(a=n.aabb||this.scene.aabb)}const u=e.poi;if(a){if(a[3]<a[0]||a[4]<a[1]||a[5]<a[2])return;if(a[3]===a[0]&&a[4]===a[1]&&a[5]===a[2])return;a=a.slice();const t=p.getAABB3Center(a);this._look2=u||t;const s=p.subVec3(this._eye1,this._look1,Oa),n=p.normalizeVec3(s),i=u?p.getAABB3DiagPoint(a,u):p.getAABB3Diag(a),r=e.fitFOV||this._fitFOV,l=Math.abs(i/Math.tan(r*p.DEGTORAD));this._orthoScale2=1.1*i,this._eye2[0]=this._look2[0]+n[0]*l,this._eye2[1]=this._look2[1]+n[1]*l,this._eye2[2]=this._look2[2]+n[2]*l,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(r||l||o)&&(this._flyingEyeLookUp=!!r&&!!l&&!!o,this._flyingEye=!!r&&!l,this._flyingLook=!!l&&!r,r&&(this._eye2[0]=r[0],this._eye2[1]=r[1],this._eye2[2]=r[2]),l&&(this._look2[0]=l[0],this._look2[1]=l[1],this._look2[2]=l[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));i?("ortho"===e.projection&&"ortho"!==n.projection&&(this._projection2="ortho",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.ortho.matrix.slice(),n.projection="customProjection"),"perspective"===e.projection&&"perspective"!==n.projection&&(this._projection2="perspective",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.perspective.matrix.slice(),n.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,R.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var s,n,i,a,r;if(e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye||e.look||e.up)i=e.eye,a=e.look,r=e.up;else{let t=e;if((m.isNumeric(t)||m.isString(t))&&(n=t,t=this.scene.components[n],!t))return void this.error("Component not found: "+m.inQuotes(n));s=t.aabb||this.scene.aabb}const l=e.poi;if(s){if(s[3]<=s[0]||s[4]<=s[1]||s[5]<=s[2])return;var o=l?p.getAABB3DiagPoint(s,l):p.getAABB3Diag(s);let n;a=l||p.getAABB3Center(s,a),this._trail?p.subVec3(t.look,a,La):p.subVec3(t.eye,t.look,La),p.normalizeVec3(La);n=(void 0!==e.fit?e.fit:this._fit)?Math.abs(o/Math.tan((e.fitFOV||this._fitFOV)*p.DEGTORAD)):p.lenVec3(p.subVec3(t.eye,t.look,Oa)),p.mulVec3Scalar(La,n),t.eye=p.addVec3(a,La,Oa),t.look=a,this.scene.camera.ortho.scale=1.1*o}else(i||a||r)&&(i&&(t.eye=i),a&&(t.look=a),r&&(t.up=r));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const s=this.easing?Ma._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(p.subVec3(n.eye,n.look,La),n.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,Na),n.look=p.subVec3(Na,La,Sa)):this._flyingLook&&(n.look=p.lerpVec3(s,0,1,this._look1,this._look2,Sa),n.up=p.lerpVec3(s,0,1,this._up1,this._up2,xa)):this._flyingEyeLookUp&&(n.eye=p.lerpVec3(s,0,1,this._eye1,this._eye2,Na),n.look=p.lerpVec3(s,0,1,this._look1,this._look2,Sa),n.up=p.lerpVec3(s,0,1,this._up1,this._up2,xa)),this._projection2){const t="ortho"===this._projection2?Ma._easeOutExpo(e,0,1,1):Ma._easeInCubic(e,0,1,1);n.customProjection.matrix=p.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();R.scheduleTask(this._update,this)}static _ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}static _easeInCubic(e,t,s,n){return s*(e/=n)*e*e+t}static _easeOutExpo(e,t,s,n){return s*(1-Math.pow(2,-10*e/n))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class Fa extends _{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new Ma(this),this._t=0,this.state=Fa.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const n=performance.now(),i=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==i)switch(this.state){case Fa.SCRUBBING:return;case Fa.PLAYING:if(this._t+=this._playingRate*i,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=Fa.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case Fa.PLAYING_TO:s=this._t+this._playingRate*i*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=Fa.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=Fa.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=Fa.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const n=s.frames[e];n?(this.state=Fa.SCRUBBING,this._cameraFlightAnimation.flyTo(n,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=Fa.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=Fa.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=Fa.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}Fa.STOPPED=0,Fa.SCRUBBING=1,Fa.PLAYING=2,Fa.PLAYING_TO=3;const Ha=p.vec3(),Ua=p.vec3();p.vec3();const Ga=p.vec3([0,-1,0]),Va=p.vec4([0,0,0,1]);class ja extends _{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=p.vec3(),this._origin=p.vec3(),this._rtcPos=p.vec3(),this._dir=p.vec3(),this._size=1,this._imageSize=p.vec2(),this._texture=new Zi(this),this._plane=new vi(this,{geometry:new Rt(this,oa({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new St(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new vi(this,{geometry:new Rt(this,la({size:1,divisions:10})),material:new St(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Mi(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),S(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,s=[-this._dir[0],-this._dir[1],-this._dir[2]];p.subVec3(t,this.position,Ha);const n=-p.dotVec3(s,Ha);p.normalizeVec3(s),p.mulVec3Scalar(s,n,Ua),p.vec3PairToQuaternion(Ga,e,Va),this._node.quaternion=Va}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],s=this._imageSize[1];if(t>s){const n=s/t;this._node.scale=[e,1,e*n]}else{const n=t/s;this._node.scale=[e*n,1,e]}}}class ka extends At{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const s=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const n=this.scene.camera,i=this.scene.canvas;this._onCameraViewMatrix=n.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=n.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=i.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new We({type:"point",pos:p.vec3([1,1,1]),color:p.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=p.identityMat4());const e=s._state.pos,t=n.look,i=n.up;p.lookAtMat4v(e,t,i,s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:()=>{if(s._shadowProjMatrixDirty){s._shadowProjMatrix||(s._shadowProjMatrix=p.identityMat4());const e=s.scene.canvas.canvas;p.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1}return s._shadowProjMatrix},getShadowRenderBuf:()=>(s._shadowRenderBuf||(s._shadowRenderBuf=new Ue(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function Qa(e){if(!Wa(e.width)||!Wa(e.height)){const t=document.createElement("canvas");t.width=za(e.width),t.height=za(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Wa(e){return 0==(e&e-1)}function za(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Ka extends _{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const s=this.scene.canvas.gl;this._state=new We({texture:new zi({gl:s,target:s.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),d.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,s=this.scene.canvas.gl;this._images=[];let n=!1,i=0;for(let a=0;a<e.length;a++){const r=new Image;r.onload=function(){let e=r;const l=a;return function(){if(!n&&(e=Qa(e),t._images[l]=e,i++,6===i)){let e=t._state.texture;e||(e=new zi({gl:s,target:s.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),r.onerror=function(){n=!0},r.src=e[a]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),d.memory.textures--,this._state.destroy()}}class Ya extends Ka{get type(){return"ReflectionMap"}constructor(e,t={}){super(e,t),this.scene._lightsState.addReflectionMap(this._state),this.scene._reflectionMapCreated(this)}destroy(){super.destroy(),this.scene._reflectionMapDestroyed(this)}}class Xa extends Ka{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}}class qa extends q{constructor(e,t={}){super(e,{entity:t.entity,occludable:t.occludable,worldPos:t.worldPos}),this._occluded=!1,this._visible=!0,this._src=null,this._image=null,this._pos=p.vec3(),this._origin=p.vec3(),this._rtcPos=p.vec3(),this._dir=p.vec3(),this._size=1,this._imageSize=p.vec2(),this._texture=new Zi(this,{src:t.src}),this._geometry=new Rt(this,{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),this._mesh=new vi(this,{geometry:this._geometry,material:new St(this,{ambient:[.9,.3,.9],shininess:30,diffuseMap:this._texture,backfaces:!0}),scale:[1,1,1],position:t.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),this.visible=!0,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,this.size=t.size,t.image?this.image=t.image:this.src=t.src}_setVisible(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,super._setVisible(e)}set visible(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}get visible(){return this._visible}set image(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],s=this._imageSize[1],n=s/t;this._geometry.positions=t>s?[e,e*n,0,-e,e*n,0,-e,-e*n,0,e,-e*n,0]:[e/n,e,0,-e/n,e,0,-e/n,-e,0,e/n,-e,0]}}class Ja{constructor(e){this._eye=p.vec3(),this._look=p.vec3(),this._up=p.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,s=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:s.fov,fovAxis:s.fovAxis,near:s.near,far:s.far};break;case"ortho":this._projection={projection:"ortho",scale:s.scale,near:s.near,far:s.far};break;case"frustum":this._projection={projection:"frustum",left:s.left,right:s.right,top:s.top,bottom:s.bottom,near:s.near,far:s.far};break;case"custom":this._projection={projection:"custom",matrix:s.matrix.slice()}}}restoreCamera(e,t){const s=e.camera,n=this._projection;function i(){switch(n.type){case"perspective":s.perspective.fov=n.fov,s.perspective.fovAxis=n.fovAxis,s.perspective.near=n.near,s.perspective.far=n.far;break;case"ortho":s.ortho.scale=n.scale,s.ortho.near=n.near,s.ortho.far=n.far;break;case"frustum":s.frustum.left=n.left,s.frustum.right=n.right,s.frustum.top=n.top,s.frustum.bottom=n.bottom,s.frustum.near=n.near,s.frustum.far=n.far;break;case"custom":s.customProjection.matrix=n.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:n.scale,projection:n.projection},(()=>{i(),t()})):(s.eye=this._eye,s.look=this._look,s.up=this._up,i(),s.projection=n.projection)}}const Za=p.vec3();class $a{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,s){const n=t.rootMetaObject;if(!n)return;const i=n.getObjectIDsInSubtree();this.numObjects=0,this._mask=s?m.apply(s,{}):null;const a=e.objects,r=!s||s.visible,l=!s||s.edges,o=!s||s.xrayed,c=!s||s.highlighted,u=!s||s.selected,h=!s||s.clippable,p=!s||s.pickable,A=!s||s.colorize,d=!s||s.opacity;for(var f=0,I=i.length;f<I;f++){const e=a[i[f]];if(e){if(r&&(this.objectsVisible[f]=e.visible),l&&(this.objectsEdges[f]=e.edges),o&&(this.objectsXrayed[f]=e.xrayed),c&&(this.objectsHighlighted[f]=e.highlighted),u&&(this.objectsSelected[f]=e.selected),h&&(this.objectsClippable[f]=e.clippable),p&&(this.objectsPickable[f]=e.pickable),A){const t=e.colorize;this.objectsColorize[3*f+0]=t[0],this.objectsColorize[3*f+1]=t[1],this.objectsColorize[3*f+2]=t[2]}d&&(this.objectsOpacity[f]=e.opacity),this.numObjects++}}}restoreObjects(e,t){const s=t.rootMetaObject;if(!s)return;const n=s.getObjectIDsInSubtree(),i=this._mask,a=!i||i.visible,r=!i||i.edges,l=!i||i.xrayed,o=!i||i.highlighted,c=!i||i.selected,u=!i||i.clippable,h=!i||i.pickable,p=!i||i.colorize,A=!i||i.opacity,d=e.objects;for(var f=0,I=n.length;f<I;f++){const e=d[n[f]];e&&(a&&(e.visible=this.objectsVisible[f]),r&&(e.edges=this.objectsEdges[f]),l&&(e.xrayed=this.objectsXrayed[f]),o&&(e.highlighted=this.objectsHighlighted[f]),c&&(e.selected=this.objectsSelected[f]),u&&(e.clippable=this.objectsClippable[f]),h&&(e.pickable=this.objectsPickable[f]),p&&(Za[0]=this.objectsColorize[3*f+0],Za[1]=this.objectsColorize[3*f+1],Za[2]=this.objectsColorize[3*f+2],e.colorize=Za),A&&(e.opacity=this.objectsOpacity[f]))}}}const er=p.vec3();class tr{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?m.apply(t,{}):null;const s=e.objects,n=!t||t.visible,i=!t||t.edges,a=!t||t.xrayed,r=!t||t.highlighted,l=!t||t.selected,o=!t||t.clippable,c=!t||t.pickable,u=!t||t.colorize,h=!t||t.opacity;for(let e in s)if(s.hasOwnProperty(e)){const t=s[e],p=this.numObjects;if(n&&(this.objectsVisible[p]=t.visible),i&&(this.objectsEdges[p]=t.edges),a&&(this.objectsXrayed[p]=t.xrayed),r&&(this.objectsHighlighted[p]=t.highlighted),l&&(this.objectsSelected[p]=t.selected),o&&(this.objectsClippable[p]=t.clippable),c&&(this.objectsPickable[p]=t.pickable),u){const e=t.colorize;e?(this.objectsColorize[3*p+0]=e[0],this.objectsColorize[3*p+1]=e[1],this.objectsColorize[3*p+2]=e[2],this.objectsHasColorize[p]=!0):this.objectsHasColorize[p]=!1}h&&(this.objectsOpacity[p]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,s=!t||t.visible,n=!t||t.edges,i=!t||t.xrayed,a=!t||t.highlighted,r=!t||t.selected,l=!t||t.clippable,o=!t||t.pickable,c=!t||t.colorize,u=!t||t.opacity;var h=0;const p=e.objects;for(let e in p)if(p.hasOwnProperty(e)){const t=p[e];s&&(t.visible=this.objectsVisible[h]),n&&(t.edges=this.objectsEdges[h]),i&&(t.xrayed=this.objectsXrayed[h]),a&&(t.highlighted=this.objectsHighlighted[h]),r&&(t.selected=this.objectsSelected[h]),l&&(t.clippable=this.objectsClippable[h]),o&&(t.pickable=this.objectsPickable[h]),c&&(this.objectsHasColorize[h]?(er[0]=this.objectsColorize[3*h+0],er[1]=this.objectsColorize[3*h+1],er[2]=this.objectsColorize[3*h+2],t.colorize=er):t.colorize=null),u&&(t.opacity=this.objectsOpacity[h]),h++}}}class sr extends Ra{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.v3=t.v3,this.t=t.t}set v0(e){this._v0=e||p.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||p.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||p.vec3([0,0,0])}get v2(){return this._v2}set v3(e){this.fire("v3",this._v3=e||p.vec3([0,0,0]))}get v3(){return this._v3}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=p.vec3();return t[0]=p.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=p.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=p.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class nr extends Ra{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,s,n;for(e=e||[],s=0,n=this._curves.length;s<n;s++)(t=this._curves[s]).off(this._dirtySubs[s]),t.off(this._destroyedSubs[s]);this._curves=[],this._dirtySubs=[],this._destroyedSubs=[];var i=this;function a(){i._dirty=!0}function r(){var e=this.id;for(s=0,n=i._curves.length;s<n;s++)if(i._curves[s].id===e)return i._curves=i._curves.slice(s,s+1),i._dirtySubs=i._dirtySubs.slice(s,s+1),i._destroyedSubs=i._destroyedSubs.slice(s,s+1),void(i._dirty=!0)}for(s=0,n=e.length;s<n;s++){if(t=e[s],m.isNumeric(t)||m.isString(t)){var l=t;if(!(t=this.scene.components[l])){this.error("Component not found: "+_inQuotes(l));continue}}var o=t.type;"xeokit.SplineCurve"===o||"xeokit.Path"===o||"xeokit.CubicBezierCurve"===o||"xeokit.QuadraticBezierCurve"===o?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",a)),this._destroyedSubs.push(t.once("destroyed",r))):this.error("Component "+_inQuotes(t.id)+" is not a xeokit.SplineCurve, xeokit.Path or xeokit.QuadraticBezierCurve")}this._dirty=!0}get curves(){return this._curves}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,s=e*this.length,n=this._getCurveLengths(),i=0;i<n.length;){if(n[i]>=s){var a=1-(n[i]-s)/(t=this._curves[i]).length;return t.getPointAt(a)}i++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],s=0,n=this._curves.length;for(e=0;e<n;e++)s+=this._curves[e].length,t.push(s);return this._cachedLengths=t,this._dirty=!1,t}_getJSON(){for(var e=[],t=0,s=this._curves.length;t<s;t++)e.push(this._curves[t].id);return{curves:e,t:this._t}}destroy(){var e,t,s;for(super.destroy(),e=0,t=this._curves.length;e<t;e++)(s=this._curves[e]).off(this._dirtySubs[e]),s.off(this._destroyedSubs[e])}}class ir extends Ra{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.t=t.t}set v0(e){this._v0=e||p.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||p.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||p.vec3([0,0,0])}get v2(){return this._v2}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=p.vec3();return t[0]=p.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=p.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=p.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class ar{constructor(e,t,s,n,i=null,a=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.aabb=null,this.layer=i,this.portionId=a,this._color=[s[0],s[1],s[2],n],this._colorize=[s[0],s[1],s[2],n],this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,n=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),n&&this.layer.setTransparent(this.portionId,t,s)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,n){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,s,n)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const rr=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let lr=0;const or={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},cr=new Float32Array([1,1,1,1]),ur=new Float32Array([0,0,0,1]),hr=p.vec4(),pr=p.vec3();class Ar{constructor(e,t=!1,{instancing:s=!1,edges:n=!1}={}){this._scene=e,this._withSAO=t,this._instancing=s,this._edges=n,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:s}=t.canvas,{model:n,layerIndex:i}=e,a=t._sectionPlanesState.sectionPlanes.length;if(a>0){const r=t._sectionPlanesState.sectionPlanes,l=i*a,o=n.renderFlags;for(let t=0;t<a;t++){const n=this._uSectionPlanes[t];if(n){const i=o.sectionPlanesActivePerLayer[l+t];if(s.uniform1i(n.active,i?1:0),i){const i=r[t],a=e._state.origin;if(a){const e=L(i.dist,i.dir,a,pr);s.uniform3fv(n.pos,e)}else s.uniform3fv(n.pos,i.pos);s.uniform3fv(n.dir,i.dir)}}}}}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uColor||(this._uColor=n.getLocation("silhouetteColor")),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uGammaFactor=n.getLocation("gammaFactor"),t.uniformBlockBinding(n.handle,t.getUniformBlockIndex(n.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=n.getLocation("zFar")),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)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aMetallicRoughness=n.getAttribute("metallicRoughness"),this._aFlags=n.getAttribute("flags"),this._aPickColor=n.getAttribute("pickColor"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrixCol0=n.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=n.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=n.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=n.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=n.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=n.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=n.getLocation("intensityRange")),this._uPointSize=n.getLocation("pointSize"),this._uNearPlaneHeight=n.getLocation("nearPlaneHeight")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState,a=i.lights,r=t.camera.project;n.bind(),e.textureUnit=0,this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[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;hr[0]=t,hr[1]=i,hr[2]=n.blendCutoff,hr[3]=n.blendFactor,s.uniform4fv(this._uSAOParams,hr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor),this._uPickInvisible&&s.uniform1i(this._uPickInvisible,e.pickInvisible),this._uShadowViewMatrix&&s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),this._uShadowProjMatrix&&s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix)}_makeVAO(e){const t=this._scene.canvas.gl,s=t.createVertexArray();return t.bindVertexArray(s),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer((this._instancing,e.positionsBuf)),this._aUV&&this._aUV.bindArrayBuffer((this._instancing,e.uvBuf)),this._aNormal&&this._aNormal.bindArrayBuffer((this._instancing,e.normalsBuf)),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer((e.colorsBuf,e.colorsBuf)),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),s}drawLayer(e,t,s,{colorUniform:n=!1,incrementDrawState:i=!1}={}){const a=pe.MAX_TEXTURE_IMAGE_UNITS,r=this._scene,l=r.canvas.gl,{_state:o,model:c}=t,{textureSet:u,origin:h,positionsDecodeMatrix:p}=o,A=r._lightsState,d=r.pointsMaterial,{camera:f}=c.scene,{viewNormalMatrix:I,project:y}=f,m=e.pickViewMatrix||f.viewMatrix,{worldMatrix:v,worldNormalMatrix:w}=c;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?l.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(o));let g=0;if(this._matricesUniformBlockBufferData.set(v,0),this._matricesUniformBlockBufferData.set(h?O(m,h):m,g+=16),this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,g+=16),this._matricesUniformBlockBufferData.set(p,g+=16),this._matricesUniformBlockBufferData.set(w,g+=16),this._matricesUniformBlockBufferData.set(I,g+=16),l.bindBuffer(l.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),l.bufferData(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,l.DYNAMIC_DRAW),l.bindBufferBase(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),l.uniform1i(this._uRenderPass,s),this.setSectionPlanesStateUniforms(t),r.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&l.uniform1f(this._uZFar,r.camera.project.far)}if(this._uPickInvisible&&l.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&l.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&l.uniform1f(this._uPickZFar,e.pickZFar),this._uPositionsDecodeMatrix&&l.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&l.uniformMatrix3fv(this._uUVDecodeMatrix,!1,(this._instancing,o.uvDecodeMatrix)),this._uIntensityRange&&d.filterIntensity&&l.uniform2f(this._uIntensityRange,d.minIntensity,d.maxIntensity),this._uPointSize&&l.uniform1f(this._uPointSize,d.pointSize),this._uNearPlaneHeight){const e="ortho"===r.camera.projection?1:l.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));l.uniform1f(this._uNearPlaneHeight,e)}if(u){const{colorTexture:t,metallicRoughnessTexture:s,emissiveTexture:n,normalsTexture:i,occlusionTexture:r}=u;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uMetallicRoughMap&&s&&(this._program.bindTexture(this._uMetallicRoughMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uEmissiveMap&&n&&(this._program.bindTexture(this._uEmissiveMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uNormalMap&&i&&(this._program.bindTexture(this._uNormalMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uAOMap&&r&&(this._program.bindTexture(this._uAOMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a)}if(A.reflectionMaps.length>0&&A.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,A.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),A.lightMaps.length>0&&A.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,A.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),this._withSAO){const t=r.sao;if(t.possible){const s=l.drawingBufferWidth,n=l.drawingBufferHeight;hr[0]=s,hr[1]=n,hr[2]=t.blendCutoff,hr[3]=t.blendFactor,l.uniform4fv(this._uSAOParams,hr),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++}}if(n){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===or[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=r.xrayMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===or[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=r.highlightMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===or[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=r.selectedMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else l.uniform4fv(this._uColor,this._edges?ur:cr)}this._draw({state:o,frameCtx:e,incrementDrawState:i}),l.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class dr extends Ar{constructor(e,t,{instancing:s=!1,edges:n=!1}={}){super(e,t,{instancing:s,edges:n})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=n.pickElementsCount||s.indicesBuf.numItems,a=n.pickElementsOffset?n.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,a),i&&n.drawElements++}}}class fr extends dr{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Ir extends Ar{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++)}}class yr extends Ir{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class mr extends Ar{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),i&&n.drawArrays++}}class vr extends Ar{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),i&&n.drawArrays++}}class wr extends Ar{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),i&&n.drawElements++}}class gr extends Ar{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++}}class Tr extends dr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// Triangles batching draw vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;");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+";")));a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;");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(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 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("vFlags = flags;")),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("// Triangles batching 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;")),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Er extends dr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),n){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(i),i.push("uniform vec4 lightAmbient;");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];"ambient"!==s.type&&(i.push("uniform vec4 lightColor"+e+";"),"dir"===s.type&&i.push("uniform vec3 lightDir"+e+";"),"point"===s.type&&i.push("uniform vec3 lightPos"+e+";"),"spot"===s.type&&(i.push("uniform vec3 lightPos"+e+";"),i.push("uniform vec3 lightDir"+e+";")))}if(i.push("in vec4 vViewPosition;"),i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}i.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),i.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),i.push("float lambertian = 1.0;"),i.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),i.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),i.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];if("ambient"!==s.type){if("dir"===s.type)"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===s.type)"view"===s.space?i.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):i.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==s.type)continue;"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}i.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),i.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return i.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):i.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class br extends dr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching silhouette fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = vColor;"),a.push("}"),a}}class Dr extends fr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Pr extends fr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Rr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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("in float vFlags;");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 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vPickColor; "),n.push("}"),n}}class Cr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 batching 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("in float vFlags;");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 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class _r extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 batching pick normals 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("in float vFlags;");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 vec3 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Br extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),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 batching occlusion 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Or extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching depth fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),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("in float vFlags;");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("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("const float shiftRight8 = 1.0 / 256.;"),n.push("vec4 packDepthToRGBA( const in float v ) {"),n.push(" vec4 r = vec4( fract( v * packFactors ), v );"),n.push(" r.yzw -= r.xyz * shiftRight8;"),n.push(" return r * packUpScale;"),n.push("}"),n.push("in vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&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}}class Sr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Nr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<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("in vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class xr extends dr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Triangles batching quality draw 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("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),a.push("vFragDepth = 1.0 + clipPos.w;")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Triangles batching quality draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),r.push("uniform sampler2D uAOMap;"),r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),r.push(" return surf_norm;"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("float aoFactor = texture(uAOMap, vUV).r;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Lr extends dr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 batching pick flat normals 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Mr extends dr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,n=e._sectionPlanesState,i=n.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching color texture fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),i){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(a),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("in vec4 vViewPosition;"),a.push("in vec4 vColor;"),a.push("in vec2 vUV;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.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("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?a.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):a.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),a.push("float opacity = color.a;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):a.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&a.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Fr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Tr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Tr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Er(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Er(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Mr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Mr(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new xr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new xr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new br(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Or(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Sr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Dr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Pr(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Rr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new _r(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Lr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Cr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Br(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Nr(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Hr={};class Ur{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Gr=p.mat4(),Vr=p.mat4();function jr(e,t,s){const n=e.length,i=new Uint16Array(n),a=t[0],r=t[1],l=t[2],o=t[3]-a,c=t[4]-r,u=t[5]-l,h=65525,A=h/o,d=h/c,f=h/u,I=e=>e>=0?e:0;for(let t=0;t<n;t+=3)i[t+0]=Math.floor(I(e[t+0]-a)*A),i[t+1]=Math.floor(I(e[t+1]-r)*d),i[t+2]=Math.floor(I(e[t+2]-l)*f);return p.identityMat4(Gr),p.translationMat4v(t,Gr),p.identityMat4(Vr),p.scalingMat4v([o/h,c/h,u/h],Vr),p.mulMat4(Gr,Vr,s),i}function kr(e,t){const s=e[0],n=e[1],i=e[2],a=e[3]-s,r=e[4]-n,l=e[5]-i,o=65525;return p.identityMat4(Gr),p.translationMat4v(e,Gr),p.identityMat4(Vr),p.scalingMat4v([a/o,r/o,l/o],Vr),p.mulMat4(Gr,Vr,t),t}function Qr(e,t,s){let n=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),i=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=n,t=i;e=(1-Math.abs(i))*(n>=0?1:-1),t=(1-Math.abs(n))*(i>=0?1:-1),n=e,i=t}return new Int8Array([Math[t](127.5*n+(n<0?-1:0)),Math[s](127.5*i+(i<0?-1:0))])}function Wr(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}const zr=p.vec3();class Kr{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;let c=a.eye;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const u=t.aabb,h=[p.safeInv(u[3]-u[0])*p.MAX_INT,p.safeInv(u[4]-u[1])*p.MAX_INT,p.safeInv(u[5]-u[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(h[0]),e.snapPickCoordinateScale[1]=p.safeInv(h[1]),e.snapPickCoordinateScale[2]=p.safeInv(h[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),e.pickViewMatrix&&(c=e.pickOrigin||c);const A=[c[0]-o[0],c[1]-o[1],c[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,h),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible),r.uniform1i(this._uSolid,t.solid);const d=e.pickViewMatrix||a.viewMatrix,f=o?O(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),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 I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;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=L(s.dist,s.dir,o,zr);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.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0),l.indicesBuf.unbind()}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(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._uSolid=s.getLocation("solid"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform bool solid;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;")),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// VBO SnapBatchingDepthBufInitRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yr=p.vec3();class Xr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}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;e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2];const c=t.aabb,u=[p.safeInv(c[3]-c[0])*p.MAX_INT,p.safeInv(c[4]-c[1])*p.MAX_INT,p.safeInv(c[5]-c[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(u[0]),e.snapPickCoordinateScale[1]=p.safeInv(u[1]),e.snapPickCoordinateScale[2]=p.safeInv(u[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());let h=a.eye;e.pickViewMatrix&&(h=e.pickOrigin||h);const A=[h[0]-o[0],h[1]-o[1],h[2]-o[2]];r.uniform3fv(this._uCameraEyeRtc,A),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,u),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||a.viewMatrix,f=o?O(d,o):d;if(r.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),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 I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,a=n.renderFlags;for(let t=0;t<I;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=L(s.dist,s.dir,o,Yr);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.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(l.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(l.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(l.flagsBuf),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElements(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0),l.edgeIndicesBuf.unbind()):r.drawArrays(r.POINTS,0,l.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(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,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapBatchingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class qr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Kr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Xr(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Jr={};const Zr=p.mat4(),$r=p.mat4(),el=p.vec4([0,0,0,1]),tl=p.vec4([0,0,0,1]),sl=p.vec4([0,0,0,1]),nl=p.OBB3(),il=p.vec3(),al=p.vec3(),rl=p.vec3(),ll=p.vec3(),ol=p.vec3(),cl=p.vec3(),ul=p.vec3();class hl{constructor(e){console.log("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Hr[t];return s||(s=new Fr(e),Hr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Hr[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=Jr[t];return s||(s=new qr(e),Jr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Jr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Ur(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new We({origin:p.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=p.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=p.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=p.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.normals,i=e.normalsCompressed,a=e.uv,r=e.uvCompressed,l=e.colors,o=e.colorsCompressed,c=e.indices,u=e.edgeIndices,h=e.color,A=e.metallic,d=e.roughness,f=e.opacity,I=e.meshMatrix,y=e.sceneModelMatrix,m=e.worldAABB,v=e.pickColor,w=this.model.scene,g=this._buffer,T=g.positions.length/3;let E;if(this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";E=s.length/3;for(let e=0,t=s.length;e<t;e++)g.positions.push(s[e]);const e=bt.getPositionsBounds(s),t=bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);m[0]=t[0],m[1]=t[1],m[2]=t[2],m[3]=n[0],m[4]=n[1],m[5]=n[2],y&&(p.AABB3ToOBB3(m,nl),p.transformOBB3(y,nl),p.OBB3ToAABB3(nl,m))}else{if(!t)throw"positions expected";E=t.length/3;const e=t.length,s=g.positions.length;for(let e=0,s=t.length;e<s;e++)g.positions.push(t[e]);if(I)for(let t=s,n=s+e;t<n;t+=3)el[0]=g.positions[t+0],el[1]=g.positions[t+1],el[2]=g.positions[t+2],p.transformPoint4(I,el,tl),g.positions[t+0]=tl[0],g.positions[t+1]=tl[1],g.positions[t+2]=tl[2],p.expandAABB3Point3(this._modelAABB,tl),y?(p.transformPoint4(y,tl,sl),p.expandAABB3Point3(m,sl)):p.expandAABB3Point3(m,tl);else for(let t=s,n=s+e;t<n;t+=3)el[0]=g.positions[t+0],el[1]=g.positions[t+1],el[2]=g.positions[t+2],p.expandAABB3Point3(this._modelAABB,el),y?(p.transformPoint4(y,el,tl),p.expandAABB3Point3(m,tl)):p.expandAABB3Point3(m,el)}if(this._state.origin){const e=this._state.origin;m[0]+=e[0],m[1]+=e[1],m[2]+=e[2],m[3]+=e[0],m[4]+=e[1],m[5]+=e[2]}if(p.expandAABB3(this.aabb,m),i&&i.length>0)for(let e=0,t=i.length;e<t;e++)g.normals.push(i[e]);else if(n&&n.length>0){const e=Zr;I?p.inverseMat4(p.transposeMat4(I,$r),e):p.identityMat4(e,e),function(e,t,s,n,i){function a(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let r,l,o,c,u,h,A=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(h=0;h<s;h+=3)A[0]=t[h],A[1]=t[h+1],A[2]=t[h+2],p.transformVec3(e,A,d),p.normalizeVec3(d,d),o=r=Qr(d,"floor","floor"),l=Wr(r),c=u=a(d,l),r=Qr(d,"ceil","floor"),l=Wr(r),c=a(d,l),c>u&&(o=r,u=c),r=Qr(d,"floor","ceil"),l=Wr(r),c=a(d,l),c>u&&(o=r,u=c),r=Qr(d,"ceil","ceil"),l=Wr(r),c=a(d,l),c>u&&(o=r,u=c),n[i+h+0]=o[0],n[i+h+1]=o[1],n[i+h+2]=0}(e,n,n.length,g.normals,g.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(255*l[e]),g.colors.push(255*l[e+1]),g.colors.push(255*l[e+2]),g.colors.push(255);else if(o)for(let e=0,t=l.length;e<t;e+=3)g.colors.push(l[e]),g.colors.push(l[e+1]),g.colors.push(l[e+2]),g.colors.push(255);else if(h){const e=h[0],t=h[1],s=h[2],n=f;for(let i=0;i<E;i++)g.colors.push(e),g.colors.push(t),g.colors.push(s),g.colors.push(n)}const b=null!=A?A:0,D=null!=d?d:255;for(let e=0;e<E;e++)g.metallicRoughness.push(b),g.metallicRoughness.push(D);if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)g.uv.push(a[e]);else if(r&&r.length>0)for(let e=0,t=r.length;e<t;e++)g.uv.push(r[e]);for(let e=0,t=c.length;e<t;e++)g.indices.push(T+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)g.edgeIndices.push(T+u[e]);{const e=g.pickColors.length;for(let t=e,s=e+4*E;t<s;t+=4)g.pickColors.push(v[0]),g.pickColors.push(v[1]),g.pickColors.push(v[2]),g.pickColors.push(v[3])}if(w.entityOffsetsEnabled)for(let e=0;e<E;e++)g.offsets.push(0),g.offsets.push(0),g.offsets.push(0);const P=this._portions.length,R={vertsBaseIndex:T,numVerts:E,indicesBaseIndex:g.indices.length-c.length,numIndices:c.length};return w.pickSurfacePrecisionEnabled&&(R.indices=c,w.entityOffsetsEnabled&&(R.offset=new Float32Array(3))),this._portions.push(R),this._numPortions++,this.model.numPortions++,this._numVerts+=R.numVerts,P}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0){const n=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):jr(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=p.mat4());if(e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],s=3*t.vertsBaseIndex,i=s+3*t.numVerts;t.quantizedPositions=n.slice(s,i)}}if(s.normals.length>0){const n=new Int8Array(s.normals);let i=!0;e.normalsBuf=new De(t,t.ARRAY_BUFFER,n,s.normals.length,3,t.STATIC_DRAW,i)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.uv.length>0)if(e.uvDecodeMatrix){let n=!1;e.uvBuf=new De(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,n)}else{const n=bt.getUVBounds(s.uv),i=bt.compressUVs(s.uv,n.min,n.max),a=i.quantized;let r=!1;e.uvDecodeMatrix=p.mat3(i.decodeMatrix),e.uvBuf=new De(t,t.ARRAY_BUFFER,a,a.length,2,t.STATIC_DRAW,r)}if(s.metallicRoughness.length>0){const n=new Uint8Array(s.metallicRoughness);let i=!1;e.metallicRoughnessBuf=new De(t,t.ARRAY_BUFFER,n,s.metallicRoughness.length,2,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n),a=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const n=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,n,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,n=this._portions[s],i=4*n.vertsBaseIndex,a=4*n.numVerts,r=this._scratchMemory.getUInt8Array(a),l=t[0],o=t[1],c=t[2],u=t[3];for(let e=0;e<a;e+=4)r[e+0]=l,r[e+1]=o,r[e+2]=c,r[e+3]=u;this._state.colorsBuf&&this._state.colorsBuf.setData(r,i,a)}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){if(!this._finalized)throw"Not finalized";const i=e,a=this._portions[i],r=a.vertsBaseIndex,l=a.numVerts,o=!!(t&M),c=!!(t&V),u=!!(t&j),h=!!(t&k),p=!!(t&Q),A=!!(t&H),d=!!(t&F);let f,I;f=!o||d||c||u&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,I=!o||d?or.NOT_RENDERED:h?or.SILHOUETTE_SELECTED:u?or.SILHOUETTE_HIGHLIGHTED:c?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let y=0;y=!o||d?or.NOT_RENDERED:h?or.EDGES_SELECTED:u?or.EDGES_HIGHLIGHTED:c?or.EDGES_XRAYED:p?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let m=o&&!d&&A?or.PICK:or.NOT_RENDERED;const v=t&U?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=r,t=r+l;e<t;e++){let t=0;t|=f,t|=I<<4,t|=y<<8,t|=m<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(l);for(let t=0;t<l;t++){let s=0;s|=f,s|=I<<4,s|=y<<8,s|=m<<12,s|=v<<16,e[t]=s}this._state.flagsBuf.setData(e,r,l)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=e,n=this._portions[s],i=3*n.vertsBaseIndex,a=3*n.numVerts,r=this._scratchMemory.getFloat32Array(a),l=t[0],o=t[1],c=t[2];for(let e=0;e<a;e+=3)r[e+0]=l,r[e+1]=o,r[e+2]=c;this._state.offsetsBuf&&this._state.offsetsBuf.setData(r,i,a),this.model.scene.pickSurfacePrecisionEnabled&&(n.offset[0]=t[0],n.offset[1]=t[1],n.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return;const s=this._state,n=this._portions[e];if(!n)return void this.model.error("portion not found: "+e);const i=n.quantizedPositions,a=s.origin,r=n.offset,l=a[0]+r[0],o=a[1]+r[1],c=a[2]+r[2],u=el;for(let e=0,n=i.length;e<n;e+=3)u[0]=i[e],u[1]=i[e+1],u[2]=i[e+2],u[3]=1,p.decompressPosition(u,s.positionsDecodeMatrix),p.transformPoint4(this.model.worldMatrix,u),u[0]+=l,u[1]+=o,u[2]+=c,t(u)}getElementsCountAndOffset(e){let t=null,s=null;const n=this._portions[e];return n&&(t=n.numIndices,s=n.indicesBaseIndex),{count:t,offset:s}}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?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRendererWithSAO&&this._batchingRenderers.pbrRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRendererWithSAO&&this._batchingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._batchingRenderers.flatColorRendererWithSAO&&this._batchingRenderers.flatColorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||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),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,or.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._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,or.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._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsFlatRenderer&&this._batchingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,or.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthBufInitRenderer&&this._snapBatchingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,or.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthRenderer&&this._snapBatchingRenderers.snapDepthRenderer.drawLayer(t,this,or.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state,r=this._portions[e];if(!r)return this.model.error("portion not found: "+e),!1;const l=r.quantizedPositions,o=r.indices,c=a.origin,u=r.offset,h=il,A=al;h.set(c?p.subVec3(t,c,rl):t),A.set(s),u&&p.subVec3(h,u),p.transformRay(this.model.worldNormalMatrix,h,A,h,A);const d=ll,f=ol,I=cl;let y=!1,m=0;const v=ul;for(let e=0,s=o.length;e<s;e+=3){const s=3*o[e],r=3*o[e+1],w=3*o[e+2];if(d[0]=l[s],d[1]=l[s+1],d[2]=l[s+2],f[0]=l[r],f[1]=l[r+1],f[2]=l[r+2],I[0]=l[w],I[1]=l[w+1],I[2]=l[w+2],p.decompressPosition(d,a.positionsDecodeMatrix),p.decompressPosition(f,a.positionsDecodeMatrix),p.decompressPosition(I,a.positionsDecodeMatrix),p.rayTriangleIntersect(h,A,d,f,I,v)){p.transformPoint3(this.model.worldMatrix,v,v),u&&p.addVec3(v,u),c&&p.addVec3(v,c);const e=Math.abs(p.lenVec3(p.subVec3(v,t,[])));(!y||e>m)&&(m=e,n.set(v),i&&p.triangleNormal(d,f,I,i),y=!0)}}return y&&i&&(p.transformVec3(this.model.worldNormalMatrix,i,i),p.normalizeVec3(i)),y}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class pl extends Ir{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i,a,r;const l=[];for(l.push("#version 300 es"),l.push("// Instancing geometry drawing vertex shader"),l.push("uniform int renderPass;"),l.push("in vec3 position;"),l.push("in vec2 normal;"),l.push("in vec4 color;"),l.push("in float flags;"),e.entityOffsetsEnabled&&l.push("in vec3 offset;"),l.push("in vec4 modelMatrixCol0;"),l.push("in vec4 modelMatrixCol1;"),l.push("in vec4 modelMatrixCol2;"),l.push("in vec4 modelNormalMatrixCol0;"),l.push("in vec4 modelNormalMatrixCol1;"),l.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(l,!0),e.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;")),l.push("uniform vec4 lightAmbient;"),i=0,a=s.lights.length;i<a;i++)r=s.lights[i],"ambient"!==r.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===r.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===r.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===r.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")));for(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.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);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"),n&&(l.push("out vec4 vWorldPosition;"),l.push("out float vFlags;")),l.push("out vec4 vColor;"),l.push("void main(void) {"),l.push("int colorFlag = int(flags) & 0xF;"),l.push("if (colorFlag != renderPass) {"),l.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),l.push("} else {"),l.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),l.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&l.push(" worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix * worldPosition; "),l.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),l.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),l.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),i=0,a=s.lights.length;i<a;i++)if(r=s.lights[i],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}return l.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),l.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),l.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(l.push("vWorldPosition = worldPosition;"),l.push("vFlags = flags;")),l.push("gl_Position = clipPos;"),l.push("}"),l.push("}"),l}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Al extends Ir{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let n,i;const a=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry flat-shading drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),a){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];"ambient"!==e.type&&(r.push("uniform vec4 lightColor"+n+";"),"dir"===e.type&&r.push("uniform vec3 lightDir"+n+";"),"point"===e.type&&r.push("uniform vec3 lightPos"+n+";"),"spot"===e.type&&(r.push("uniform vec3 lightPos"+n+";"),r.push("uniform vec3 lightDir"+n+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),a){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}for(r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?r.push("viewLightDir = -normalize(lightPos"+n+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+n+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+n+".rgb * lightColor"+n+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class dl extends Ir{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing fill 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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class fl extends yr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class Il extends yr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),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("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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}}class yl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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("in float vFlags;");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 vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = vPickColor; "),n.push("}"),n}}class ml extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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 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("in float vFlags;");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 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 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class vl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = 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"),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("in float vFlags;");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 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class wl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),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("// Instancing occlusion 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("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class gl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry depth drawing fragment shader"),a.push("precision highp float;"),a.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec2 vHighPrecisionZW;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),a.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),a.push("}"),a}}class Tl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class El extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}const bl={3e3:"linearToLinear",3001:"sRGBToLinear"};class Dl extends Ir{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Instancing geometry quality drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.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);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push(" worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),a.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),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("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Instancing geometry quality drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),r.push(" return normalize(surf_norm );"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = "+bl[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = "+bl[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Pl extends Ir{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = 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"),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("in float vFlags;");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 vWorldNormal;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&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(" outColor = vec4((worldNormal * 0.5) + 0.5, 1.0);"),n.push("}"),n}}class Rl extends Ir{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState;let i,a;const r=s.sectionPlanes.length>0,l=[];if(l.push("#version 300 es"),l.push("// Instancing geometry drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),e.logarithmicDepthBufferEnabled&&(l.push("in float isPerspective;"),l.push("uniform float logDepthBufFC;"),l.push("in float vFragDepth;")),l.push("uniform sampler2D uColorMap;"),this._withSAO&&(l.push("uniform sampler2D uOcclusionTexture;"),l.push("uniform vec4 uSAOParams;"),l.push("const float packUpscale = 256. / 255.;"),l.push("const float unpackDownScale = 255. / 256.;"),l.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),l.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),l.push("float unpackRGBToFloat( const in vec4 v ) {"),l.push(" return dot( v, unPackFactors );"),l.push("}")),l.push("uniform float gammaFactor;"),l.push("vec4 linearToLinear( in vec4 value ) {"),l.push(" return value;"),l.push("}"),l.push("vec4 sRGBToLinear( in vec4 value ) {"),l.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),l.push("}"),l.push("vec4 gammaToLinear( in vec4 value) {"),l.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),l.push("}"),t&&(l.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),r){l.push("in vec4 vWorldPosition;"),l.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("uniform bool sectionPlaneActive"+e+";"),l.push("uniform vec3 sectionPlanePos"+e+";"),l.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(l),l.push("uniform vec4 lightAmbient;"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];"ambient"!==e.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===e.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===e.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===e.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")))}if(l.push("in vec4 vViewPosition;"),l.push("in vec4 vColor;"),l.push("in vec2 vUV;"),l.push("out vec4 outColor;"),l.push("void main(void) {"),r){l.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),l.push(" if (clippable) {"),l.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("if (sectionPlaneActive"+e+") {"),l.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),l.push("}");l.push(" if (dist > 0.0) { "),l.push(" discard;"),l.push(" }"),l.push("}")}for(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),l.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),l.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),l.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}}return l.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?l.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):l.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),l.push("float opacity = color.a;"),this._withSAO?(l.push(" float viewportWidth = uSAOParams[0];"),l.push(" float viewportHeight = uSAOParams[1];"),l.push(" float blendCutoff = uSAOParams[2];"),l.push(" float blendFactor = uSAOParams[3];"),l.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),l.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb * ambient, opacity);")):l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb, opacity);"),t&&l.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&l.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),l.push("}"),l}}class Cl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new pl(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new pl(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Al(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Al(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Dl(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Dl(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Rl(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Rl(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new dl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new gl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Tl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new fl(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Il(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new yl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new vl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Pl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ml(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new wl(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new El(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const _l={};const Bl=p.vec3();class Ol{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.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[p.safeInv(o[3]-o[0])*p.MAX_INT,p.safeInv(o[4]-o[1])*p.MAX_INT,p.safeInv(o[5]-o[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(c[0]),e.snapPickCoordinateScale[1]=p.safeInv(c[1]),e.snapPickCoordinateScale[2]=p.safeInv(c[2]),!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let h=u.eye;e.pickViewMatrix&&(h=e.pickOrigin||h);const A=[h[0]-l[0],h[1]-l[1],h[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?O(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=L(s.dist,s.dir,l,Bl);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags&&(this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),r.indicesBuf.bind(),a.drawElementsInstanced(a.TRIANGLES,r.indicesBuf.numItems,r.indicesBuf.itemType,0,r.numInstances),r.indicesBuf.unbind(),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.z += 0.0001;"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Sl=p.vec3();class Nl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,s){const n=t.model,i=n.scene,a=i.canvas.gl,r=t._state,l=t._state.origin;e.snapPickOrigin[0]=l[0],e.snapPickOrigin[1]=l[1],e.snapPickOrigin[2]=l[2];const o=t.aabb,c=[p.safeInv(o[3]-o[0])*p.MAX_INT,p.safeInv(o[4]-o[1])*p.MAX_INT,p.safeInv(o[5]-o[2])*p.MAX_INT];if(e.snapPickCoordinateScale[0]=p.safeInv(c[0]),e.snapPickCoordinateScale[1]=p.safeInv(c[1]),e.snapPickCoordinateScale[2]=p.safeInv(c[2]),!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const u=i.camera;let h=u.eye;e.pickViewMatrix&&(h=e.pickOrigin||h);const A=[h[0]-l[0],h[1]-l[1],h[2]-l[2]];a.uniform3fv(this._uCameraEyeRtc,A),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,c),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);const d=e.pickViewMatrix||u.viewMatrix,f=l?O(d,l):d;if(a.uniformMatrix4fv(this._uViewMatrix,!1,f),a.uniformMatrix4fv(this._uWorldMatrix,!1,n.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,u.projMatrix),i.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const I=i._sectionPlanesState.sectionPlanes.length;if(I>0){const e=i._sectionPlanesState.sectionPlanes,s=t.layerIndex*I,r=n.renderFlags;for(let t=0;t<I;t++){const n=this._uSectionPlanes[t];if(n){const i=r.sectionPlanesActivePerLayer[s+t];if(a.uniform1i(n.active,i?1:0),i){const s=e[t];if(l){const e=L(s.dist,s.dir,l,Sl);a.uniform3fv(n.pos,e)}else a.uniform3fv(n.pos,s.pos);a.uniform3fv(n.dir,s.dir)}}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(r.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(r.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(r.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aFlags.bindArrayBuffer(r.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1),this._aOffset&&(this._aOffset.bindArrayBuffer(r.offsetsBuf),a.vertexAttribDivisor(this._aOffset.location,1)),"edge"===e.snapMode?(r.edgeIndicesBuf.bind(),a.drawElementsInstanced(a.LINES,r.edgeIndicesBuf.numItems,r.edgeIndicesBuf.itemType,0,r.numInstances),r.edgeIndicesBuf.unbind()):a.drawArraysInstanced(a.POINTS,0,r.positionsBuf.numItems,r.numInstances),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,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._aFlags=s.getAttribute("flags"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),this.uVectorA=s.getLocation("snapVectorA"),this.uInverseVectorAB=s.getLocation("snapInvVectorAB"),this._uLayerNumber=s.getLocation("layerNumber"),this._uCoordinateScaler=s.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),e.logarithmicDepthBufferEnabled&&(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,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// SnapInstancingDepthRenderer 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 int layerNumber;"),n.push("uniform vec3 coordinateScaler;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 highp vec3 relativeToOriginPosition;"),n.push("out highp ivec4 outCoords;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),n.push("}"),n}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class xl{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new Ol(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new Nl(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const Ll={};const Ml=new Uint8Array(4),Fl=new Float32Array(1),Hl=p.vec4([0,0,0,1]),Ul=p.vec4([0,0,0,1]),Gl=p.vec4([0,0,0,1]),Vl=new Float32Array(3),jl=p.vec3(),kl=p.vec3(),Ql=p.vec3(),Wl=p.vec3(),zl=p.vec3(),Kl=p.vec3(),Yl=p.vec3();class Xl{constructor(e){console.log("Creating TrianglesInstancingLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=_l[t];return s||(s=new Cl(e),_l[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete _l[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=Ll[t];return s||(s=new xl(e),Ll[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Ll[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new We({numInstances:0,obb:p.OBB3(),origin:p.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=p.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,n=e.roughness,i=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,a=e.meshMatrix,r=e.sceneModelMatrix,l=e.aabb,o=e.pickColor;if(this._finalized)throw"Already finalized";const c=t[0],u=t[1],h=t[2];if(this._colors.push(c),this._colors.push(u),this._colors.push(h),this._colors.push(i),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(a[0]),this._modelMatrixCol0.push(a[4]),this._modelMatrixCol0.push(a[8]),this._modelMatrixCol0.push(a[12]),this._modelMatrixCol1.push(a[1]),this._modelMatrixCol1.push(a[5]),this._modelMatrixCol1.push(a[9]),this._modelMatrixCol1.push(a[13]),this._modelMatrixCol2.push(a[2]),this._modelMatrixCol2.push(a[6]),this._modelMatrixCol2.push(a[10]),this._modelMatrixCol2.push(a[14]),this._state.geometry.normals){let e=p.transposeMat4(a,p.mat4()),t=p.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(o[0]),this._pickColors.push(o[1]),this._pickColors.push(o[2]),this._pickColors.push(o[3]);const A=this._state.geometry.positionsCompressed.length,d=this._state.geometry.positionsCompressed,f=this._state.geometry.positionsDecodeMatrix;for(let e=0;e<A;e+=3)Hl[0]=d[e+0],Hl[1]=d[e+1],Hl[2]=d[e+2],p.transformPoint4(f,Hl,Ul),p.transformPoint4(a,Ul,Hl),r?(p.transformPoint4(r,Hl,Gl),p.expandAABB3Point3(l,Gl)):p.expandAABB3Point3(l,Hl);if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}p.expandAABB3(this.aabb,l),this._state.numInstances++;const I=this._portions.length,y={};return this.model.scene.pickSurfacePrecisionEnabled&&(y.matrix=a.slice(),y.inverseMatrix=null,y.normalMatrix=null),this._portions.push(y),this._numPortions++,this.model.numPortions++,I}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,s=e.textureSet,n=this.model.scene.canvas.gl,i=this._colors.length,a=i/4;if(i>0){let t=!1;e.colorsBuf=new De(n,n.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,n.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new De(n,n.ARRAY_BUFFER,t,this._metallicRoughness.length,2,n.STATIC_DRAW,s)}if(a>0){let t=!1;e.flagsBuf=new De(n,n.ARRAY_BUFFER,new Float32Array(a),a,1,n.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,n.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new De(n,n.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,n.STATIC_DRAW,s),e.positionsDecodeMatrix=p.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),i=!1;e.colorsBuf=new De(n,n.ARRAY_BUFFER,s,s.length,4,n.STATIC_DRAW,i)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new De(n,n.ARRAY_BUFFER,s,s.length,2,n.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,n.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new De(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,n.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelMatrixCol1Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelMatrixCol2Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new De(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new De(n,n.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,n.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ml[0]=t[0],Ml[1]=t[1],Ml[2]=t[2],Ml[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Ml,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&M),i=!!(t&V),a=!!(t&j),r=!!(t&k),l=!!(t&Q),o=!!(t&H),c=!!(t&F);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,h=!n||c?or.NOT_RENDERED:r?or.SILHOUETTE_SELECTED:a?or.SILHOUETTE_HIGHLIGHTED:i?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let p=0;p=!n||c?or.NOT_RENDERED:r?or.EDGES_SELECTED:a?or.EDGES_HIGHLIGHTED:i?or.EDGES_XRAYED:l?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?or.PICK:or.NOT_RENDERED)<<12,A|=(t&U?1:0)<<16,Fl[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(Fl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Vl[0]=t[0],Vl[1]=t[1],Vl[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Vl,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,n=s.geometry,i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const a=n.quantizedPositions,r=s.origin,l=i.offset,o=r[0]+l[0],c=r[1]+l[1],u=r[2]+l[2],h=Hl,A=i.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=a.length;e<s;e+=3)h[0]=a[e],h[1]=a[e+1],h[2]=a[e+2],p.decompressPosition(h,f),p.transformPoint3(A,h),p.transformPoint3(d,h),h[0]+=o,h[1]+=c,h[2]+=u,t(h)}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?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRendererWithSAO&&this._instancingRenderers.pbrRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRendererWithSAO&&this._instancingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):this._instancingRenderers.flatColorRendererWithSAO&&this._instancingRenderers.flatColorRendererWithSAO.drawLayer(t,this,or.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||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),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,or.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._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,or.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._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,or.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,or.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,or.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(t,this,or.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthBufInitRenderer&&this._snapInstancingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,or.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthRenderer&&this._snapInstancingRenderers.snapDepthRenderer.drawLayer(t,this,or.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state.geometry,r=this._state,l=this._portions[e];if(!l)return this.model.error("portion not found: "+e),!1;l.inverseMatrix||(l.inverseMatrix=p.inverseMat4(l.matrix,p.mat4())),i&&!l.normalMatrix&&(l.normalMatrix=p.transposeMat4(l.inverseMatrix,p.mat4()));const o=a.quantizedPositions,c=a.indices,u=r.origin,h=l.offset,A=jl,d=kl;A.set(u?p.subVec3(t,u,Ql):t),d.set(s),h&&p.subVec3(A,h),p.transformRay(this.model.worldNormalMatrix,A,d,A,d),p.transformRay(l.inverseMatrix,A,d,A,d);const f=Wl,I=zl,y=Kl;let m=!1,v=0;const w=Yl;for(let e=0,s=c.length;e<s;e+=3){const s=3*c[e+0],a=3*c[e+1],g=3*c[e+2];f[0]=o[s],f[1]=o[s+1],f[2]=o[s+2],I[0]=o[a],I[1]=o[a+1],I[2]=o[a+2],y[0]=o[g],y[1]=o[g+1],y[2]=o[g+2];const{positionsDecodeMatrix:T}=r.geometry;if(p.decompressPosition(f,T),p.decompressPosition(I,T),p.decompressPosition(y,T),p.rayTriangleIntersect(A,d,f,I,y,w)){p.transformPoint3(l.matrix,w,w),p.transformPoint3(this.model.worldMatrix,w,w),h&&p.addVec3(w,h),u&&p.addVec3(w,u);const e=Math.abs(p.lenVec3(p.subVec3(w,t,[])));(!m||e>v)&&(v=e,n.set(w),i&&p.triangleNormal(f,I,y,i),m=!0)}}return m&&i&&(p.transformVec3(l.normalMatrix,i,i),p.transformVec3(this.model.worldNormalMatrix,i,i),p.normalizeVec3(i)),m}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ql extends wr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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 n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Jl extends wr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Zl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ql(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Jl(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const $l={};class eo{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const to=p.vec4([0,0,0,1]),so=p.vec4([0,0,0,1]),no=p.vec4([0,0,0,1]),io=p.OBB3();class ao{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=$l[t];return s||(s=new Zl(e),$l[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete $l[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new eo(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new We({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:p.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=p.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.indices,i=e.color,a=e.opacity,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB;e.pickColor;const c=this._buffer,u=c.positions.length/3;let h;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";h=s.length/3;for(let e=0,t=s.length;e<t;e++)c.positions.push(s[e]);const e=bt.getPositionsBounds(s),t=bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(p.AABB3ToOBB3(o,io),p.transformOBB3(l,io),p.OBB3ToAABB3(io,o))}else{if(!t)throw"positions expected";h=t.length/3;const e=t.length,s=c.positions.length;for(let e=0,s=t.length;e<s;e++)c.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)to[0]=c.positions[t+0],to[1]=c.positions[t+1],to[2]=c.positions[t+2],p.transformPoint4(r,to,so),c.positions[t+0]=so[0],c.positions[t+1]=so[1],c.positions[t+2]=so[2],p.expandAABB3Point3(this._modelAABB,so),l?(p.transformPoint4(l,so,no),p.expandAABB3Point3(o,no)):p.expandAABB3Point3(o,so);else for(let t=s,n=s+e;t<n;t+=3)to[0]=c.positions[t+0],to[1]=c.positions[t+1],to[2]=c.positions[t+2],p.expandAABB3Point3(this._modelAABB,to),l?(p.transformPoint4(l,to,so),p.expandAABB3Point3(o,so)):p.expandAABB3Point3(o,to)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(p.expandAABB3(this.aabb,o),i){const e=i[0],t=i[1],s=i[2],n=a;for(let i=0;i<h;i++)c.colors.push(e),c.colors.push(t),c.colors.push(s),c.colors.push(n)}if(n)for(let e=0,t=n.length;e<t;e++)c.indices.push(n[e]+u);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<h;e++)c.offsets.push(0),c.offsets.push(0),c.offsets.push(0);const A=this._portions.length/2;return this._portions.push(u),this._portions.push(h),this._numPortions++,this.model.numPortions++,this._numVerts+=h,A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=jr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.colors.length>0){const n=s.colors.length/4,i=new Float32Array(n);let a=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new De(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2],c=t[3];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o,a[e+3]=c;this._state.colorsBuf.setData(a,n,i)}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){if(!this._finalized)throw"Not finalized";const i=2*e,a=this._portions[i],r=this._portions[i+1],l=!!(t&M),o=!!(t&V),c=!!(t&j),u=!!(t&k),h=!!(t&H),p=!!(t&F);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,d=!l||p?or.NOT_RENDERED:u?or.SILHOUETTE_SELECTED:c?or.SILHOUETTE_HIGHLIGHTED:o?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let f=l&&!p&&h?or.PICK:or.NOT_RENDERED;const I=t&U?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=a,t=a+r;e<t;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(r);for(let t=0;t<r;t++){let s=0;s|=A,s|=d<<4,s|=f<<12,s|=I<<16,e[t]=s}this._state.flagsBuf.setData(e,a,r)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class ro extends gr{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Lines instancing color fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class lo extends gr{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class oo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ro(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new lo(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const co={};const uo=new Uint8Array(4),ho=new Float32Array(1),po=p.vec4([0,0,0,1]),Ao=p.vec4([0,0,0,1]),fo=p.vec4([0,0,0,1]),Io=new Float32Array(3);class yo{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=co[t];return s||(s=new oo(e),co[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete co[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new We({obb:p.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=p.vec3(e.origin)),this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,n=e.meshMatrix,i=e.worldMatrix,a=e.aabb;if(this._finalized)throw"Already finalized";const r=t[0],l=t[1],o=t[2];t[3],this._colors.push(r),this._colors.push(l),this._colors.push(o),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),p.collapseAABB3(a);const c=this._state.obb,u=c.length;for(let e=0;e<u;e+=4)po[0]=c[e+0],po[1]=c[e+1],po[2]=c[e+2],p.transformPoint4(n,po,Ao),i?(p.transformPoint4(i,Ao,fo),p.expandAABB3Point3(a,fo)):p.expandAABB3Point3(a,Ao);if(this._state.origin){const e=this._state.origin;a[0]+=e[0],a[1]+=e[1],a[2]+=e[2],a[3]+=e[0],a[4]+=e[1],a[5]+=e[2]}p.expandAABB3(this.aabb,a),this._state.numInstances++;const h=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,h}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,s=t/4;if(t>0){let t=!1;this._state.colorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";uo[0]=t[0],uo[1]=t[1],uo[2]=t[2],uo[3]=t[3],this._state.colorsBuf.setData(uo,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&M),i=!!(t&V),a=!!(t&j),r=!!(t&k),l=!!(t&Q),o=!!(t&H),c=!!(t&F);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,h=!n||c?or.NOT_RENDERED:r?or.SILHOUETTE_SELECTED:a?or.SILHOUETTE_HIGHLIGHTED:i?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let p=0;p=!n||c?or.NOT_RENDERED:r?or.EDGES_SELECTED:a?or.EDGES_HIGHLIGHTED:i?or.EDGES_XRAYED:l?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?or.PICK:or.NOT_RENDERED)<<12,A|=(t&U?255:0)<<16,ho[0]=A,this._state.flagsBuf.setData(ho,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Io[0]=t[0],Io[1]=t[1],Io[2]=t[2],this._state.offsetsBuf.setData(Io,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class mo extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,n=[];return n.push("#version 300 es"),n.push("// Points batching color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&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("// Points batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class vo extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform vec4 color;"),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points batching silhouette vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("uniform vec4 color;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = color;"),a.push("}"),a}}class wo extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),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("// Points batching pick mesh vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class go extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batched pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),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("// Points batched 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("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("in float vFlags;");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 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 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class To extends mr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push(" gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points batching occlusion 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Eo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new mo(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new vo(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wo(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new go(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new To(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const bo={};class Do{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const Po=p.vec4(),Ro=p.vec4(),Co=p.vec4([0,0,0,1]),_o=p.vec4([0,0,0,1]),Bo=p.vec4([0,0,0,1]),Oo=p.OBB3();class So{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=bo[t];return s||(s=new Eo(e),bo[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete bo[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Do(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new We({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:p.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=p.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=p.vec3(e.origin)),this.aabb=p.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.color,i=e.colorsCompressed,a=e.colors,r=e.meshMatrix,l=e.worldMatrix,o=e.worldAABB,c=e.pickColor,u=this._buffer,h=u.positions.length/3;let A;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e<t;e++)u.positions.push(s[e]);const e=bt.getPositionsBounds(s),t=bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,Po),n=bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,Ro);o[0]=t[0],o[1]=t[1],o[2]=t[2],o[3]=n[0],o[4]=n[1],o[5]=n[2],l&&(p.AABB3ToOBB3(o,Oo),p.transformOBB3(l,Oo),p.OBB3ToAABB3(Oo,o)),A=s.length/3}else{if(!t)throw"positions expected";A=t.length/3;const e=t.length,s=u.positions.length;for(let e=0,s=t.length;e<s;e++)u.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)Co[0]=u.positions[t+0],Co[1]=u.positions[t+1],Co[2]=u.positions[t+2],p.transformPoint4(r,Co,_o),u.positions[t+0]=_o[0],u.positions[t+1]=_o[1],u.positions[t+2]=_o[2],p.expandAABB3Point3(this._modelAABB,_o),l?(p.transformPoint4(l,_o,Bo),p.expandAABB3Point3(o,Bo)):p.expandAABB3Point3(o,_o);else for(let t=s,n=s+e;t<n;t+=3)Co[0]=u.positions[t+0],Co[1]=u.positions[t+1],Co[2]=u.positions[t+2],p.expandAABB3Point3(this._modelAABB,Co),l?(p.transformPoint4(l,Co,_o),p.expandAABB3Point3(o,_o)):p.expandAABB3Point3(o,Co)}if(this._state.origin){const e=this._state.origin;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}if(p.expandAABB3(this.aabb,o),i)for(let e=0,t=i.length;e<t;e++)u.colors.push(i[e]);else if(a)for(let e=0,t=a.length;e<t;e++)u.colors.push(255*a[e]);else if(n){const e=n[0],t=n[1],s=n[2],i=1;for(let n=0;n<A;n++)u.colors.push(e),u.colors.push(t),u.colors.push(s),u.colors.push(i)}{const e=u.pickColors.length;for(let t=e,s=e+4*A;t<s;t+=4)u.pickColors.push(c[0]),u.pickColors.push(c[1]),u.pickColors.push(c[2]),u.pickColors.push(c[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)u.offsets.push(0),u.offsets.push(0),u.offsets.push(0);const d=this._portions.length/2;return this._portions.push(h),this._portions.push(A),this._numPortions++,this.model.numPortions++,d}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=jr(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new De(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new De(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n);let a=!1;e.flagsBuf=new De(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new De(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new De(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=2*e,i=this._portions[n],a=this._portions[n+1],r=this._scratchMemory.getFloat32Array(a),l=!!(t&M),o=!!(t&V),c=!!(t&j),u=!!(t&k),h=!!(t&H),p=!!(t&F);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,d=!l||p?or.NOT_RENDERED:u?or.SILHOUETTE_SELECTED:c?or.SILHOUETTE_HIGHLIGHTED:o?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let f=l&&!p&&h?or.PICK:or.NOT_RENDERED;const I=t&U?1:0;for(let e=0;e<a;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,r[e]=t}this._state.flagsBuf.setData(r,i)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class No extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&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("// Points instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class xo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 color;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),n.push("uniform vec4 silhouetteColor;"),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Lo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class Mo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push(" vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing 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("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("in float vFlags;");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 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 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Fo extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 color;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),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("// Points instancing occlusion vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;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 n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Ho extends vr{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points instancing depth vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("const float packUpScale = 256. / 255.;"),a.push("const float unpackDownscale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),a.push("const float shiftRight8 = 1.0 / 256.;"),a.push("vec4 packDepthToRGBA( const in float v ) {"),a.push(" vec4 r = vec4( fract( v * packFactors ), v );"),a.push(" r.yzw -= r.xyz * shiftRight8;"),a.push(" return r * packUpScale;"),a.push("}"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return a.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Uo extends vr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");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 vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),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 = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Go{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new No(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ho(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Lo(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Mo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Fo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Uo(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Vo={};const jo=new Uint8Array(4),ko=new Float32Array(1),Qo=p.vec4([0,0,0,1]),Wo=p.vec4([0,0,0,1]),zo=p.vec4([0,0,0,1]),Ko=new Float32Array(3);class Yo{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=Vo[t];return s||(s=new Go(e),Vo[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Vo[t],s._destroy()}))),s}(e.model.scene),this._aabb=p.collapseAABB3(),this._state=new We({obb:p.OBB3(),numInstances:0,origin:e.origin?p.vec3(e.origin):null,geometry:e.geometry,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=p.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.worldMatrix,n=e.aabb,i=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(i[0]),this._pickColors.push(i[1]),this._pickColors.push(i[2]),this._pickColors.push(i[3]),p.collapseAABB3(n);const a=this._state.obb,r=a.length;for(let e=0;e<r;e+=4)Qo[0]=a[e+0],Qo[1]=a[e+1],Qo[2]=a[e+2],p.transformPoint4(t,Qo,Wo),s?(p.transformPoint4(s,Wo,zo),p.expandAABB3Point3(n,zo)):p.expandAABB3Point3(n,Wo);if(this._state.origin){const e=this._state.origin;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}p.expandAABB3(this.aabb,n),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4;if(t>0){let s=!1;this._state.flagsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new De(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;this._state.pickColorsBuf=new De(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&M&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&j&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&V&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&k&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&U&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Q&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&H&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&F&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&M?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&j?(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&V?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&k?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&U?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&H?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&F?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";jo[0]=t[0],jo[1]=t[1],jo[2]=t[2],this._state.colorsBuf.setData(jo,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&M),i=!!(t&V),a=!!(t&j),r=!!(t&k),l=!!(t&Q),o=!!(t&H),c=!!(t&F);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?or.NOT_RENDERED:s?or.COLOR_TRANSPARENT:or.COLOR_OPAQUE,h=!n||c?or.NOT_RENDERED:r?or.SILHOUETTE_SELECTED:a?or.SILHOUETTE_HIGHLIGHTED:i?or.SILHOUETTE_XRAYED:or.NOT_RENDERED;let p=0;p=!n||c?or.NOT_RENDERED:r?or.EDGES_SELECTED:a?or.EDGES_HIGHLIGHTED:i?or.EDGES_XRAYED:l?s?or.EDGES_COLOR_TRANSPARENT:or.EDGES_COLOR_OPAQUE:or.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?or.PICK:or.NOT_RENDERED)<<12,A|=(t&U?255:0)<<16,ko[0]=A,this._state.flagsBuf.setData(ko,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ko[0]=t[0],Ko[1]=t[1],Ko[2]=t[2],this._state.offsetsBuf.setData(Ko,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,or.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,or.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,or.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,or.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,or.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class Xo{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class qo{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Jo={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Zo{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t<s;t+=2){const s=this.handlers[t],n=this.handlers[t+1];if(s.global&&(s.lastIndex=0),s.test(e))return n}return null}}const $o=new Zo;class ec{constructor(e){this.manager=void 0!==e?e:$o,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const s=this;return new Promise((function(n,i){s.load(e,n,t,i)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const tc={};class sc extends ec{constructor(e){super(e)}load(e,t,s,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=Jo.get(e);if(void 0!==i)return this.manager.itemStart(e),setTimeout((()=>{t&&t(i),this.manager.itemEnd(e)}),0),i;if(void 0!==tc[e])return void tc[e].push({onLoad:t,onProgress:s,onError:n});tc[e]=[],tc[e].push({onLoad:t,onProgress:s,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),r=this.mimeType,l=this.responseType;fetch(a).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const s=tc[e],n=t.body.getReader(),i=t.headers.get("Content-Length"),a=i?parseInt(i):0,r=0!==a;let l=0;const o=new ReadableStream({start(e){!function t(){n.read().then((({done:n,value:i})=>{if(n)e.close();else{l+=i.byteLength;const n=new ProgressEvent("progress",{lengthComputable:r,loaded:l,total:a});for(let e=0,t=s.length;e<t;e++){const t=s[e];t.onProgress&&t.onProgress(n)}e.enqueue(i),t()}}))}()}});return new Response(o)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r)));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),s=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(s);return e.arrayBuffer().then((e=>n.decode(e)))}}})).then((t=>{Jo.add(e,t);const s=tc[e];delete tc[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const s=tc[e];if(void 0===s)throw this.manager.itemError(e),t;delete tc[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onError&&n.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class nc{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:t,msg:s,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(s,n)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((s=>{const n=this._getIdleWorker();-1!==n?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=s,this.workers[n].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let ic=0;class ac{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new nc,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const n=e.capabilities;this._workerConfig={astcSupported:n.astcSupported,etc1Supported:n.etc1Supported,etc2Supported:n.etc2Supported,dxtSupported:n.dxtSupported,bptcSupported:n.bptcSupported,pvrtcSupported:n.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new sc;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new sc;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,n]).then((([e,t])=>{const s=ac.BasisWorker.toString(),n=["/* constants */","let _EngineFormat = "+JSON.stringify(ac.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(ac.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(ac.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([n])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),ic>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),ic++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((n,i)=>{const a=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:a},e))).then((e=>{const s=e.data,{mipmaps:a,width:r,height:l,format:o,type:c,error:u,dfdTransferFn:h,dfdFlags:p}=s;if("error"===c)return i(u);t.setCompressedData({mipmaps:a,props:{format:o,minFilter:1===a.length?1006:1008,magFilter:1===a.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&p)}}),n()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),ic--}}ac.BasisFormat={ETC1S:0,UASTC_4x4:1},ac.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},ac.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},ac.BasisWorker=function(){let e,t,s;const n=_EngineFormat,i=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const u=r.data;switch(u.type){case"init":e=u.config,h=u.transcoderBinary,t=new Promise((e=>{s={wasmBinary:h,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f}=function(t){const r=new s.KTX2File(new Uint8Array(t));function u(){r.close(),r.delete()}if(!r.isValid())throw u(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=r.isUASTC()?a.UASTC_4x4:a.ETC1S,p=r.getWidth(),A=r.getHeight(),d=r.getLevels(),f=r.getHasAlpha(),I=r.getDFDTransferFunc(),y=r.getDFDFlags(),{transcoderFormat:m,engineFormat:v}=function(t,s,r,u){let h,p;const A=t===a.ETC1S?l:o;for(let n=0;n<A.length;n++){const i=A[n];if(e[i.if]&&(i.basisFormat.includes(t)&&!(u&&i.transcoderFormat.length<2)&&(!i.needsPowerOfTwo||c(s)&&c(r))))return h=i.transcoderFormat[u?1:0],p=i.engineFormat[u?1:0],{transcoderFormat:h,engineFormat:p}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=i.RGBA32,p=n.RGBAFormat,{transcoderFormat:h,engineFormat:p}}(h,p,A,f);if(!p||!A||!d)throw u(),new Error("KTX2TextureTranscoder: Invalid texture");if(!r.startTranscoding())throw u(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const w=[];for(let e=0;e<d;e++){const t=r.getImageLevelInfo(e,0,0),s=t.origWidth,n=t.origHeight,i=new Uint8Array(r.getImageTranscodedSizeInBytes(e,0,0,m));if(!r.transcodeImage(i,e,0,0,m,0,-1,-1))throw u(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");w.push({data:i,width:s,height:n})}return u(),{width:p,height:A,hasAlpha:f,mipmaps:w,format:v,dfdTransferFn:I,dfdFlags:y}}(u.buffers[0]),I=[];for(let e=0;e<p.length;++e)I.push(p[e].data.buffer);self.postMessage({type:"transcode",id:u.id,width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f},I)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:u.id,error:e.message})}}))}var h}));const r=[{if:"astcSupported",basisFormat:[a.UASTC_4x4],transcoderFormat:[i.ASTC_4x4,i.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC7_M5,i.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC1,i.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1,i.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.PVRTC1_4_RGB,i.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],l=r.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),o=r.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function c(e){return e<=2||0==(e&e-1)&&0!==e}};const rc={};function lc(e){const t=e.scene.id;let s=rc[t];return s||(s=new ac({viewer:e}),rc[t]=s,e.scene.on("destroyed",(()=>{delete rc[t],s.destroy()}))),s}
11
11
  /**
12
12
  * @author https://github.com/tmarti, with support from https://tribia.com/
13
13
  * @license MIT